当前位置:  开发笔记 > 编程语言 > 正文

绘图区域中的GTK#鼠标事件

如何解决《绘图区域中的GTK#鼠标事件》经验,为你挑选了1个好方法。

我有一个DrawingArea,我想收到鼠标事件.从教程中我发现KeyPressEvent也会捕获鼠标事件.但是对于以下代码,从不调用处理程序.

static void Main ()
{
    Application.Init ();
    Gtk.Window w = new Gtk.Window ("");

    DrawingArea a = new CairoGraphic ();
    a.KeyPressEvent += KeyPressHandler;
    w.Add(a);

    w.Resize (500, 500);
    w.DeleteEvent += close_window;
    w.ShowAll ();

    Application.Run ();
}

private static void KeyPressHandler(object sender, KeyPressEventArgs args)
{
    Console.WriteLine("key press event");   
}

我通过阅读不同的论坛和教程尝试了很多东西,包括:

将EventBox添加到窗口并将DrawingArea放入事件框并订阅EventBox的KeyPressEvent.(没用)

调用AddEvents((int)Gdk.EventMask.AllEventsMask); 在任何和所有小部件上

我确实发现订阅Windows KeyPressEvent确实给了我键盘事件但不是鼠标点击事件.

单声道文档中的所有相关页面都给我错误,所以我有点卡住了



1> Piotr Zurek..:

您还应该记住,应该在DrawingArea中添加一个事件掩码:

a.AddEvents ((int) 
            (EventMask.ButtonPressMask    
            |EventMask.ButtonReleaseMask    
            |EventMask.KeyPressMask    
            |EventMask.PointerMotionMask));

所以你的最终代码看起来应该是这样的:

class MainClass
{
    static void Main ()
    {
        Application.Init ();
        Gtk.Window w = new Gtk.Window ("");

        DrawingArea a = new DrawingArea ();
        a.AddEvents ((int) EventMask.ButtonPressMask);
        a.ButtonPressEvent += delegate(object o, ButtonPressEventArgs args) {
            Console.WriteLine("Button Pressed");
        };

        w.Add(a);

        w.Resize (500, 500);
        w.DeleteEvent += close_window;
        w.ShowAll ();

        Application.Run ();
    }

    static void close_window(object o, DeleteEventArgs args) {
        Application.Quit();
        return;
    }
}

推荐阅读
mobiledu2402851323
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有