簡體   English   中英

GTK#繪圖區鼠標事件

[英]GTK# mouse event in drawing area

我有一個 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");   
}

我通過閱讀不同的論壇和教程嘗試了很多東西,包括:

向 windows 添加一個 EventBox 並將 DrawingArea 放入事件框中並訂閱 EventBox 的 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;
    }
}

如果要捕獲鼠標事件,則必須使用 ButtonPressEvent、ButtonReleaseEvent 和 MotionNotifyEvent:

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

KeyPressEvent 僅用於鍵。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM