本文介绍了在Linux上检查C ++中的按键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种简单的方法来检查是否按下了某个键,这样我就可以在线程中循环浏览它了?首选不要使用库,并且绝对不要使用ncurses.我在互联网上找不到能正常工作的东西.

Is there an easy way to check if a key is being pressed so I can loop through that in a thread? Preferred not to use a library and definitely not ncurses. There isn't a single thing working that I have found over the internet.

推荐答案

我找到了一种更简单的方法:

I find a simpler way:

#include <X11/Xlib.h>
#include <iostream>
#include "X11/keysym.h"

/**
 *
 * @param ks  like XK_Shift_L, see /usr/include/X11/keysymdef.h
 * @return
 */
bool key_is_pressed(KeySym ks) {
    Display *dpy = XOpenDisplay(":0");
    char keys_return[32];
    XQueryKeymap(dpy, keys_return);
    KeyCode kc2 = XKeysymToKeycode(dpy, ks);
    bool isPressed = !!(keys_return[kc2 >> 3] & (1 << (kc2 & 7)));
    XCloseDisplay(dpy);
    return isPressed;
}

bool ctrl_is_pressed() {
    return key_is_pressed(XK_Control_L) || key_is_pressed(XK_Control_R);
}

int main(int argc, char **argv) {
    std::cout << ctrl_is_pressed() << std::endl;
    return (0);
};

这篇关于在Linux上检查C ++中的按键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-13 15:21