Getting keyboard modifiers state using Gnome libs (GDK) fetches initial state only

痴心易碎 提交于 2019-11-29 11:33:34

You are going to need to run the GTK+ event loop for this to work. The event loop is part of GLib's main loop. When you call gtk_main(), this main loop is run. I don't know if it polls for events or has events pushed to it, but it won't ask for the keyboard state on the fly like you were trying to do.

The easiest way to set up GDK is to do it via GTK+ by using gtk_init() and gtk_main(). You can use GDK on its own, but I don't know how. You seemed to have figured it out, which works.

And instead of calling g_usleep(), which just blocks your program, you can hook a periodic timeout into the main loop. This is done with g_timeout_add(). The function that you pass to g_timeout_add() returns a Boolean value that decides whether the timer should be stopped or not, so you don't have to worry about rescheduling your function, as GLib will do that for you.

  • Indeed, I need an event loop as andlabs said in his comment. His suggestion to use GTK gtk_init() & gtk_main() works perfectly.

    /*
     * compiling: gcc `pkg-config --cflags gtk+-3.0` -o gtk_xkbmod3 gtk_xkbmod3.c `pkg-config --libs gtk+-3.0`
     */
    
    #include <gtk/gtk.h>
    
    static void update(GdkKeymap * kmap) {
        guint state;
        state = gdk_keymap_get_modifier_state(kmap);
        g_printf("%i\n", state);
    }
    
    int main (int argc, char **argv) {
    
        gtk_init(&argc, &argv);
    
        GdkKeymap * kmap;
        kmap = gdk_keymap_get_default();
    
        g_timeout_add_seconds(1, (GSourceFunc) update, kmap);
    
        gtk_main();
    
    }
    
  • I could also use GDK with GLib GMainLoop.

    /*
     * compiling: gcc `pkg-config --cflags gdk-3.0` -o gdk_xkbmod4 gdk_xkbmod4.c `pkg-config --libs gdk-3.0`
     */
    
    #include <gdk/gdk.h>
    
    GMainLoop *mainloop;
    
    static void update(GdkKeymap * kmap) {
        guint state;
        state = gdk_keymap_get_modifier_state(kmap);
        g_printf("%i\n", state);
    }
    
    int main (int argc, char **argv) {    
    
        gdk_init(&argc, &argv);
    
        GdkKeymap * kmap;
        kmap = gdk_keymap_get_default();
    
        g_timeout_add_seconds(1, (GSourceFunc) update, kmap);
    
        mainloop = g_main_loop_new(g_main_context_default(), FALSE);
        g_main_loop_run(mainloop);    
    }
    

References:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!