c++ - XGrabKeyboard 仅在程序运行时阻止键盘

标签 c++ linux qt x11

我正在编写代码来获取按下的键并阻止键盘输入。示例:如果按下 Super_L 或 Super_R 键,阻止它们打开应用程序菜单。该代码在程序打开时有效,但当程序关闭时, key 将发送到系统。示例:如果用户在程序运行时按下 Super_L 键,则不会发生任何事情,但当程序关闭时,会自动打开 Ubuntu 应用程序菜单。我该如何解决这个问题?

void hook()
{
    Display *dpy = XOpenDisplay(0);
    XEvent ev;

    if(!dpy)
    {
        qDebug() << "Error";
        return;
    }

    XGrabKeyboard(dpy, DefaultRootWindow(dpy), false, GrabModeAsync, GrabModeAsync, CurrentTime);

    forever
    {
        XNextEvent(dpy, &ev);
        switch (ev.type)
        {
        case KeyPress:
            qDebug() << "KeyPress" << XKeysymToString(XKeycodeToKeysym(dpy, ev.xkey.keycode, 0));
            break;
        case KeyRelease:
            qDebug() << "KeyRelease" << XKeysymToString(XKeycodeToKeysym(dpy, ev.xkey.keycode, 0));
            break;
        }
    }
}

最佳答案

引用the manual :

When the X server's connection to a client is closed either by an explicit call to XCloseDisplay() or by a process that exits, the X server performs the following automatic operations:

  • It disowns all selections owned by the client (see XSetSelectionOwner()).
  • It performs an XUngrabPointer() and XUngrabKeyboard() if the client has actively grabbed the pointer or the keyboard.
  • It performs an XUngrabServer() if the client has grabbed the server.
  • It releases all passive grabs made by the client.

抓取是由客户请求并授予客户的。在抓取期间,所有相关事件都会传递给抓取客户端。没有客户,就没有抢夺。

我不知道这里有什么需要修复的。如果您希望某项功能正常工作,请确保实现该功能的应用程序正在运行。

关于c++ - XGrabKeyboard 仅在程序运行时阻止键盘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14675920/

相关文章:

c++ - 如何为 QGraphicsSimpleTextItem (Qt C++) 设置背景?

c++ - 如何从计算线程到GUI线程获取结果-我需要QSharedMemory吗?

c++ - 初始化 vector 成员变量的正确方法

c++ - Linux C++ : Linker is outputting strange errors

c++ - C++中的 boolean 错误

linux - 我想将一个脚本的输出通过管道传输到将独立处理第一个脚本的输出的不同脚本?

linux - 为什么在Linux上读取实时时钟需要 super 用户权限?

python - 有没有办法在Windows 7中不使用QT编译wireshark解析器插件?

c++ - 指向堆栈分配对象和 move 构造的指针

c++ - 如何检测构造函数是否为 noexcept 并抛出析构函数