How can I get the keyboard state in Linux?

前端 未结 4 635
遥遥无期
遥遥无期 2020-12-02 14:01

I want to check if the user pressed down the Shift key when the program starts. (That means, press down the Shift key before the program is started) It\'s

4条回答
  •  广开言路
    2020-12-02 14:20

    AFAIK this cannot be done without Xlib (aka. X) with no root level permissions. Using XQueryKeymap() will do what you want. however you pointed out that X cannot be used. Regardless, opening display connection will also be required.

    #include 
    #include 
    #include 
    #include 
    
    int main()
    {
        Display* dpy = XOpenDisplay(NULL);
        char keys_return[32];
        XQueryKeymap( dpy, keys_return );
        KeyCode kc2 = XKeysymToKeycode( dpy, XK_Shift_L );
        bool bShiftPressed = !!( keys_return[ kc2>>3 ] & ( 1<<(kc2&7) ) );
        printf("Shift is %spressed\n", bShiftPressed ? "" : "not ");
        XCloseDisplay(dpy);
    }
    

提交回复
热议问题