c++ - XNextEvent 由于某种原因不起作用

标签 c++ xlib

我正在尝试使用 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/

相关文章:

c++ - 正则表达式和 boost

c++ - 使用::std::vector 创建数组

C++ 抽象函数对象在与 std::accumulate 一起使用时会导致混淆行为

c++ - 在 64 位 Debian 环境下编译 32 位 qt 源码

c - 使用 xlib 将假按键事件发送到窗口

c++ - 类析构函数错误

c++ - 类指针的动态数组

linux - 来自 Xlib : "Killed" 的消息来源

image - 煤层气图像文件格式: what is it?怎么读呢?

Python:如何使用 Xlib 在工作区之间切换?