Intercept keys with GTK

Intercept keys with GTK

Post by Amedeo Storn » Sat, 19 Feb 2000 04:00:00



Hi all,

I have a problem getting keypress and keyrelease events in gtk+ : how do I
switch off autorepeat ?

I am designing a game, and I want to know exactely when a key is pressed or
released.

Thanks in advance
Amedeo Storni

 
 
 

Intercept keys with GTK

Post by Russell Mar » Tue, 22 Feb 2000 04:00:00


Quote:> I have a problem getting keypress and keyrelease events in gtk+ : how do I
> switch off autorepeat ?

> I am designing a game, and I want to know exactely when a key is pressed or
> released.

Use gdk_key_repeat_disable() - and gdk_key_repeat_restore() to turn
them back on. You'll also want to catch focus in/out events (as well
as, ideally, things like SIGTERM) and disable/enable auto-repeat as
appropriate. (This is needed because these functions control
auto-repeat for the X server as a whole - I don't think there's a
per-window or per-program option, unfortunately, though this is a
limitation of X rather than GTK+.) Here are excerpts from something I
did this for (the GTK+ version of nc100em) which should give you the
idea:

int need_keyrep_restore=0;

..

void closedown(void)
{
..
if(need_keyrep_restore)
  gdk_key_repeat_restore();
..

Quote:}

static gint focus_change_event(GtkWidget *widget,GdkEventFocus *event)
{
if(event->in)
  gdk_key_repeat_disable(),need_keyrep_restore=1;
else
  gdk_key_repeat_restore(),need_keyrep_restore=0;
..

Quote:}

(in window-creating routine, or whatever)

/* need to get focus change events so we can fix the auto-repeat
 * when focus is changed, not just when we start/stop.
 */
gtk_signal_connect(GTK_OBJECT(window),"focus_in_event",
                (GtkSignalFunc)focus_change_event,NULL);
gtk_signal_connect(GTK_OBJECT(window),"focus_out_event",
                (GtkSignalFunc)focus_change_event,NULL);

gtk_widget_set_events(window,
        GDK_KEY_PRESS_MASK|GDK_KEY_RELEASE_MASK|GDK_FOCUS_CHANGE_MASK);

I'll leave it to you to figure out when closedown() is called. :-)

It may also be a good idea to automatically pause the game when focus
is lost, not to mention `unpressing' any this-key-is-pressed flags you
might have.

Oh, and I think strictly speaking I should be using
GTK_SIGNAL_FUNC(focus_change_event) up there, rather than
(GtkSignalFunc)focus_change_event (but both work). I must have made
the mistake of believing the GTK+ tutorial or something. :-)

Quote:> Thanks in advance
> Amedeo Storni

-Rus.