XNextEvent 由于某种原因不起作用

XNextEvent Doesn't works for some reason

本文关键字:不起作用 由于某种原因 XNextEvent      更新时间:2023-10-16

我正在尝试使用Xlib捕获关键事件。但是由于某些原因,Xnextevent不起作用。我没有收到任何错误,但是看起来我的程序卡在" Xnextevent"电话的线上。这是我的代码:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
using namespace std;

int main()
{
    XEvent event;
    KeySym key;
    char text[255];
    Display *dis;
    dis = XOpenDisplay(NULL);
    while (1) {
        XNextEvent(dis, &event);
        if (event.type==KeyPress && XLookupString(&event.xkey,text,255,&key,0) == 1) {
            if (text[0]=='q') {
                XCloseDisplay(dis);
                return 0;
            }
            printf("You pressed the %c key!n", text[0]);
        }
    }
    return 0;
}

这不是X11窗口系统的工作方式。

仔细阅读。关键是:

事件的来源是指针所在的可见窗口。

您没有创建窗口,因此您的程序未接收键盘事件。即使您创建了窗口,它也必须具有焦点:

X服务器用于报告这些事件的窗口取决于窗口在窗口层次结构中的位置以及是否禁止任何中间窗口生成这些事件。

工作示例

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
using namespace std;

int main()
{
    XEvent event;
    Display *dis;
    Window root;
    Bool owner_events = False;
    unsigned int modifiers = ControlMask | LockMask;

    dis = XOpenDisplay(NULL);
    root = XDefaultRootWindow(dis);
    unsigned int keycode = XKeysymToKeycode(dis, XK_P);
    XSelectInput(dis,root, KeyPressMask);
    XGrabKey(dis, keycode, modifiers, root, owner_events, GrabModeAsync, GrabModeAsync);
    while (1) {
        Bool QuiteCycle = False;
        XNextEvent(dis, &event);
        if (event.type == KeyPress) {
            cout << "Hot key pressed!" << endl;
            XUngrabKey(dis, keycode, modifiers, root);
            QuiteCycle = True;
        }
        if (QuiteCycle) {
            break;
        }
    }
    XCloseDisplay(dis);
    return 0;
}