tags:

views:

947

answers:

2

I have a DrawingArea which I would like to received mouse events. From the tutorials I have found that the KeyPressEvent will also catch mouse events. However for the following code the handler is never called.

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");   
}

I have tried a bunch of things from reading different forums and tutorials including:

Adding a EventBox to the windows and putting the DrawingArea in the event box and subscribing to the KeyPressEvent for the EventBox. (didn't work)

Calling AddEvents((int)Gdk.EventMask.AllEventsMask); on any and all widgets

I did find that subscribing to the Windows KeyPressEvent did give me keyboard events but not mouse click events.

All the relevant pages in the mono docs give me errors so I'm a bit stuck

A: 

If you want to catch mouse events, you have to use ButtonPressEvent, ButtonReleaseEvent and MotionNotifyEvent:

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

KeyPressEvent is just for Keys.

Manuel Ceron
+3  A: 

You should also remember that an event mask should be added to your DrawingArea:

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

So your final code should look like that:

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;
    }
}
Piotr Zurek