Re: Strange behaviour of key-event handler.




Steve Hosgood <iisteve@weeble.i2it.co.uk> writes:

> Sorry about this. I'm having a problem receiving key-press and key-release
> events from a drawing_area in a program I'm writing. I hope this isn't a
> FAQ (I *have* read the FAQ, but see no mention of it). I also read the
> source of gtktext (because it handles key-events) but got no joy there either
> apart from the general impression that I'm "doing roughly the right thing".

OK, there are various things going on here, some which are
documented and some are pretty obscure.

> static void
> keyevent_callback(GtkWidget *widget, GdkEventKey *event, gpointer data)

All signals handlers for events have a boolean return value that
indicates whether the event was handled or not. You are returning
random garbage, so the handling of focus navigation keys may
happen or it may not.

Repeat:

 All signals handlers for events have a boolean return value that
 indicates whether the event was handled or not

> 	gtk_signal_connect (GTK_OBJECT (drawing_area), "key_press_event",
> 				(GtkSignalFunc) keyevent_callback, NULL);
> 	gtk_signal_connect (GTK_OBJECT (drawing_area), "key_release_event",
> 				(GtkSignalFunc) keyevent_callback, NULL);

It also turns out that you need to use gtk_signal_connect_after()
so that the return value from your signal handler actually takes
effect. There is a default handler for key presses in GtkWidget
that will override your return value if it runs after your key
press handler, so you need to make sure that your key press
handler is run after this.

Another way of doing this is to call gtk_signal_emit_stop_by_name()
in your key handler to avoid having the default handler be called
at all.

	/* Catch focus */
	GTK_WIDGET_SET_FLAGS(drawing_area, GTK_CAN_FOCUS);
	gtk_window_set_focus (GTK_WINDOW(window), drawing_area);

gtk_window_set_focus() is an internal function.

 - Use gtk_widget_grab_focus() instead
 - gtk_widget_grab_focus() should not be called until you've
   packed things so that the widget is a child of a GtkWindow.

Note that simply setting the focus to your widget does not
prevent the user from moving the focus somewhere; if you consider
this a problem, then you probably should be catching key events
on the toplevel window instead of on a subwidget.

When I embed your code into a test program and make the various changes
suggested above, things seem to act as I would expect.

Regards,
                                        Owen



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]