Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the keyboard state in Linux?

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 a simple console program, nothing related to X.

This maybe similar to the Win32 GetKeyboardState() function.

I want to know whether I can do this and how, but not any pros and cons with accessing the terminal directly.

like image 970
Xiè Jìléi Avatar asked Sep 06 '10 08:09

Xiè Jìléi


People also ask

Where is keyboard layout in Linux?

Open the Activities overview and start typing Settings. Click on Settings. Click Keyboard in the sidebar to open the panel. Click the + button in the Input Sources section, select the language which is associated with the layout, then select a layout and press Add.

How do I know what key I pressed on my keyboard?

The Windows on-screen keyboard is a program included in Windows that shows an on-screen keyboard to test modifier keys and other special keys. For example, when pressing the Alt , Ctrl , or Shift key, the On-Screen Keyboard highlights the keys as pressed.


2 Answers

I have found a very simple way through gtk/gdk.

int main ( int argc, char *argv[], char *env[] )
{
    gtk_init(&argc, &argv);

    GdkModifierType button_state;
    gdk_window_get_pointer(NULL, NULL, NULL, &button_state);
    if(button_state & GDK_CONTROL_MASK) {
        printf("ctrl key is pressed");
    }
}
like image 162
Lyn Avatar answered Oct 17 '22 22:10

Lyn


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 <X11/Xlib.h>
#include <X11/keysym.h>
#include <stdbool.h>
#include <stdio.h>

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);
}
like image 25
MaxLZ Avatar answered Oct 17 '22 23:10

MaxLZ