c# - 绘图区中的 GTK# 鼠标事件

标签 c# .net mono 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");   
}

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

将事件框添加到窗口并将绘图区放入事件框中,并为事件框订阅 KeyPressEvent。 (没用)

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

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

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

最佳答案

您还应该记住,应该将一个事件掩码添加到您的 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;
    }
}

关于c# - 绘图区中的 GTK# 鼠标事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/650252/

相关文章:

c# - 如何在 C++ 中读取 IL

c# - 如何为 Android 构建普通的 Mono?

c# - 如何在 WPF 应用程序中动态生成标签、按钮、复选框和文本框

c# - 使用异步/等待和任务优化即发即忘

c# - 反序列化 XML 时出现 FileNotFoundException

c# - EF 代码首先是 : inherited dbcontext creates two databases

c# - 奇怪的 HttpWebResponse 错误 : ServerProtocolViolation

c# - 在c#中使用pc中的所有内核

c# - 动态构建 LINQ 查询 - 强制使用 sp_executesql 而不是原始查询

c# - OracleClient 说我的连接已关闭