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

我有一个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确实给了我键盘事件但不是鼠标点击事件。

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

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

如果要捕获鼠标事件,则必须使用ButtonPressEvent,ButtonReleaseEvent和MotionNotifyEvent:

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

KeyPressEvent仅适用于Keys。