如何在linux中编写非阻塞全局热键检测(X11)

时间:2014-07-17 14:26:02

标签: c events x11

我想通过XNextEvent捕获热键。不幸的是,这是封锁。因此我想先调用XPending,这应该由select()触发。问题是我无法从Xserver中捕获一般的按键。这有什么不对?如果我用一个窗口(like here)这样做,一切都很好。

Window _root =  DefaultRootWindow(_display);

XSelectInput(_display, _root,
             ExposureMask | KeyPressMask | KeyReleaseMask | PointerMotionMask |
             ButtonPressMask | ButtonReleaseMask  | StructureNotifyMask
             );

XMapWindow(_display, _root);
XFlush(_display);

int     x11_fd = ConnectionNumber(_display);
fd_set in_fds;
int counter =0;
int timer =0;
XEvent ev;
int ret;
struct timeval tv;
while(1) {

    FD_ZERO(&in_fds);
    FD_SET(x11_fd, &in_fds);
    assert(FD_ISSET(x11_fd, &in_fds));
    tv.tv_sec = 1;
    tv.tv_usec = 0;

    // Wait for X Event or a Timer
    if (ret = select(x11_fd+1, &in_fds, 0, 0, &tv))
    {
        printf("%d Events Received!(%d)\n",ret,  counter++);
        // Handle XEvents and flush the input
        while(XPending(_display))
            XNextEvent(_display, &ev);
    }
    else
    {
        // Handle timer here
        printf("%d Timer Fired! (%d)\n", timer++, ret);
    }
}

0 个答案:

没有答案