Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I handle keyboard events in GTK+3?

What signals/functions should I use to get keyboard input in GTK+3?

I have looked around and the only tutorials I know of that cover GTK+3 (zetcode and gnome developer) don't seem to cover that.

Anyone can point me in the right direction?

like image 565
PintoDoido Avatar asked May 21 '17 14:05

PintoDoido


People also ask

What is the purpose of GTK+ widgets?

GTK (formerly GIMP ToolKit and GTK+) is a free and open-source cross-platform widget toolkit for creating graphical user interfaces (GUIs).

What is a GTK window?

Description. A GtkWindow is a toplevel window which can contain other widgets. Windows normally have decorations that are under the control of the windowing system and allow the user to manipulate the window (resize it, move it, close it,...).


2 Answers

I will summarize here how to handle keyboard events in GTK3, which I hope will be useful since I cannot find it put together anywhere else.

Imagine you are using GTK+3 and you want your application to do something when you press the space key. This is how you do it:

  • First enable the #GDK_KEY_PRESS_MASK mask for your Gdk.Window:

    gtk_widget_add_events(window, GDK_KEY_PRESS_MASK);
    
  • Then you connect the window with the keyboard_press() function:

    g_signal_connect (G_OBJECT (window), "key_press_event",
            G_CALLBACK (my_keypress_function), NULL);
    
  • Define your keyboard_press() to something once the space key has been pressed:

    gboolean my_keypress_function (GtkWidget *widget, GdkEventKey *event, gpointer data) {
        if (event->keyval == GDK_KEY_space){
            printf("SPACE KEY PRESSED!");
            return TRUE;
        }
        return FALSE;
    }
    
like image 140
PintoDoido Avatar answered Oct 21 '22 06:10

PintoDoido


it's g_signal_connect (G_OBJECT (window), "key_press_event", G_CALLBACK (on_key_press), NULL);

like image 35
AgentChaos Avatar answered Oct 21 '22 08:10

AgentChaos