XGrabKeyboard()在事件循环外不起作用

时间:2019-01-06 15:37:26

标签: c keyboard x11 xorg

我写了一个小代码来将键盘抓到特定的窗口。当在while(1)循环中使用时,抓斗可以完美地工作。但是,在while(1)循环之前/之外使用时,它无法抓取。

我想知道这种奇怪行为的原因。

代码如下:

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

int main()
{
    Display *d;
    Window window;
    XEvent event, ev;
    int s;

    /* open connection with the server */
    d = XOpenDisplay(NULL);
    if (d == NULL)
    {
        fprintf(stderr, "Cannot open d\n");
        exit(1);
    }

    s = DefaultScreen(d);

    /* create window */
    window = XCreateSimpleWindow(d, RootWindow(d, s), 10, 10, 400, 100, 1,
                           BlackPixel(d, s), BlackPixel(d, s));

    XSelectInput(d, window, StructureNotifyMask | ExposureMask | KeyPressMask | KeyReleaseMask | Button1Mask | Button2Mask | ButtonPressMask);

    /* map (show) the window */
    XMapWindow(d, window);


    // Error here !!!!
    if(XGrabKeyboard(d, window, True, GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
        printf("Black window grabbed before loop\n");
    else
        printf("Grab Unsuccessful\n");

    /* event loop */
    while (1)
    {
        XNextEvent(d, &event);
        printf("Here at start\n");  
        if(event.type == ButtonPress)
            printf("Button Clicked\n");     

        if(event.type == KeyPress)
        {
            printf("%x key pressed\n", event.xkey.keycode);

            // exit on ESC key press 
            if ( event.xkey.keycode == 0x09 )
                break;
            if(event.xkey.keycode == 37) //Just that if LeftCtrl is pressed, grabbing happens
            {
                if(XGrabKeyboard(d, window, True, GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess)
                    printf("Black window grabbed\n");

            }
        }
    }

    /* close connection to server */
    XCloseDisplay(d);

    return 0;
}

0 个答案:

没有答案