【问题标题】:XNextEvent Doesn't works for some reasonXNextEvent 由于某种原因不起作用
【发布时间】:2014-03-06 10:44:15
【问题描述】:

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

【问题讨论】:

  • “不起作用”从不是一个好的诊断。发生了什么 ?有错误信息吗?还是意想不到的结果?请编辑您的问题,以准确说明它是如何不起作用的。
  • @hivert 很明显问题出在哪里。无需编辑
  • 也许吧,但我认为向 SO 新手解释如何提出好问题很重要。

标签: c++ xlib


【解决方案1】:

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

仔细阅读this。重点是:

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

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

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

【讨论】:

  • 我需要全局捕获键盘事件,因此当前处于活动状态的窗口无关紧要。 xlib 是否可能,或者我应该使用另一个库?谢谢!
  • @Alexweb 不确定 xlib 是否可行
【解决方案2】:

工作示例

#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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多