How to capture the KeypressEvent on a GTK Custom Widget

Keyboard in action Let’s say you want for instance to change the cursor icon when the user presses the control key on your widget. This apparently simple task almost drove me crazy.

Subscribing to the KeyPressEvent is not enough.
Using AddEvent to add the KeyPress event is not enough either.

Actually, to be able to fire the KeyPress event, your widget, like a Winform Control, needs to receive focus.

So, I set the CanFocus property to true and… it does not work!
Arhgle!….

Thanks to this link, I finally got all the requirements:

  • You need to use the AddEvent method to add the KeyPress event to your widget’s event list
  • You need to set the CanFocus to true
  • You need to subscribe to the FocusIn event and set the HasFocus property to true when it is fired
  • You need to subscribe to the FocusOut event and set the HasFocus property to false when it is fired
  • On the event you’d like the widget to receive focus (probably ButtonPress), you need to call the GrabFocus method

Then only you will be able to get the event.

    • ilovetocode
    • October 14th, 2011

    Really useful! I have been trying for hours to get this to work!

  1. No trackbacks yet.