我正在尝试使用 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 窗口系统的工作方式。
阅读this小心。关键点是:
The source of the event is the viewable window that the pointer is in.
您没有创建窗口,因此您的程序不会接收键盘事件。即使您创建了窗口,它也必须具有焦点:
The window used by the X server to report these events depends on the window's position in the window hierarchy and whether any intervening window prohibits the generation of these events.
关于c++ - XNextEvent 由于某种原因不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22222061/