Check keypress in C++ on Linux

后端 未结 2 430
春和景丽
春和景丽 2020-12-19 07:37

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 sin

2条回答
  •  没有蜡笔的小新
    2020-12-19 08:08

    I find a simpler way:

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

提交回复
热议问题