GTK#绘图区中的鼠标事件

10
我有一个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中,然后订阅EventBox的KeyPressEvent事件。(没有起作用)

对所有小部件调用AddEvents((int)Gdk.EventMask.AllEventsMask);

我发现订阅窗口的KeyPressEvent事件确实给了我键盘事件,但没有鼠标点击事件。

所有相关的mono文档页面都给了我错误,所以我有点困惑。

2个回答

16

您还应该记住,在您的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;
    }
}

注意:如果你只想处理 ButtonReleaseEvent,那么除了将 ButtonReleaseMask 添加到事件列表中,你还必须添加 ButtonPressMask。否则,你的 ButtonReleaseEvent 委托函数不会被调用。 - Vladimir Mitrovic

1

如果你想捕获鼠标事件,你必须使用ButtonPressEvent、ButtonReleaseEvent和MotionNotifyEvent:

a.ButtonPressEvent += delegate(object o, ButtonPressEventArgs args) {
    Console.WriteLine("Button Pressed");
}

KeyPressEvent 只是针对按键的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接