clinuxkeyboardx11wayland

How to detect the status of the capslock in linux programmatically


I want some way to know if the Capslock is active or not, thought I can use xet for this purpose, using pipe, by popen('xset -q | grep Capslock') I am able to find out, but I want some way by which there is no use of the commands, in the C program, is there any way to know this. One more thing I want to ask in this context, xset doens't work in the console mode in linux, I do alt+ctrl+f1 then login there and if try to run xset -q this will throw error, perhaps this can't communicate with the XWindows in console, so what solution can be for this case.


Solution

  • I want some way to know if the Capslock is active or not

    You probably want XkbGetIndicatorState. For instance:

    #include <stdio.h>
    #include <stdlib.h>
    #include <X11/XKBlib.h>
    
    /* Compile this with -lX11 */
    
    int main ()
    {
      Display *display;
      Status status;
      unsigned state;
    
      display = XOpenDisplay (getenv ("DISPLAY"));
      if (!display)
        return 1;
      
      Status ok = XkbGetIndicatorState (display, XkbUseCoreKbd, &state);
    
      XCloseDisplay (display);
    
      if (ok != Success)
        return 2;
    
      printf ("Caps Lock is %s\n", (state & 1) ? "on" : "off");
      return 0;
    }
    

    Alternatively, you can go with the same approach that is used in xset and use XkbGetNamedIndicator which is a more general function. (Since Linux 1.1.54 the indicator lights and the key state can be changed independently, but you can generally expect them to match.)