Why does XGrabKey return BadRequest?

ⅰ亾dé卋堺 提交于 2019-12-04 12:19:11

A return value of 1 does not mean that a BadRequest error occured. Xlib handles errors via an error handler, and the function will always return 1, if it returns at all.

Your code does not work because you have to do the XGrabKey on the root window (GetDefaultRootWindow(Gtk::gdk_display)). Here's a pure Xlib demo:

#include <X11/Xlib.h>
#include <X11/keysym.h>
#include <stdio.h>

int main() {
    Display *d = XOpenDisplay(0);
    Window root = DefaultRootWindow(d);
    int keycode = XKeysymToKeycode(d, XK_BackSpace);

    int rv = XGrabKey(d, keycode, AnyModifier, root, 1, GrabModeAsync, GrabModeAsync);
    printf("XGrabKey returned %d\n", rv);

    XEvent evt;
    while(1) {
        XNextEvent(d, &evt);
        printf("Got event %d\n", evt.type);
    }
}

To then capture the X11 events from GTK use gdk_window_add_filter on a NULL or on the root window and a GdkFilterFunc that processes the events associated with your global hotkey:

#include <X11/Xlib.h>
#include <X11/keysym.h>
#include <gtk/gtk.h>
#include <gdk/gdkx.h>
#include <stdio.h>

GdkFilterReturn filter(GdkXEvent *xevent, GdkEvent *event, gpointer data) {
    XKeyEvent *ev = (XKeyEvent *)xevent;
    if(ev->type == 2) {
        printf("Backspace hit.\n");
    }

    return GDK_FILTER_CONTINUE;
}

int main(int argc, char *argv[]) {
    gtk_init(&argc, &argv);

    GdkScreen *scr = gdk_screen_get_default();
    GdkWindow *groot = gdk_screen_get_root_window(scr);
    gdk_window_set_events(groot, GDK_KEY_PRESS_MASK);
    gdk_window_add_filter(groot, filter, NULL);

    Display *d = gdk_x11_get_default_xdisplay();
    Window root = GDK_WINDOW_XID(groot);
    int keycode = XKeysymToKeycode(d, XK_BackSpace);
    XGrabKey(d, keycode, AnyModifier, root, 1, GrabModeAsync, GrabModeAsync);

    gtk_main();
}

As a side note, a modifier mask of 0 means that no modifiers must be enabled, even those that would not modify the meaning of a key. A grab on the letter "A" with a 0 modifier would not match NumLock + A. That's why I used AnyModifer.

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