C++ – How to get a num lock state using C/C++

cgtklinuxx11

I have read Gdk forum link which says that getting num lock state api is implemented since version 3.0. But I am using version 2.4 and I cannot update to version 3.0 as I need to support lower Linux version. Here is the discussion link:

http://mail.gnome.org/archives/commits-list/2010-July/msg00259.html

SO, is there any other way to get the num lock state using internal Linux command?

Regards,
iSight

Best Answer

Sample code to get the NumLock state. Let foo.c be:

#include <stdio.h>
#include <X11/Xlib.h>

int main(void) {  
   Display *dpy = XOpenDisplay(":0"); 
   XKeyboardState x;
   XGetKeyboardControl(dpy, &x);
   XCloseDisplay(dpy);
   printf("led_mask=%lx\n", x.led_mask);
   printf("NumLock is %s\n", (x.led_mask & 2) ? "On" : "Off");
   return 0;
}

Then this gives, tested with CentOS 5 on a Dell laptop:

gcc foo.c -o foo -lX11
foo
led_mask=2
NumLock is On

Or you could do something with popen("xset q | grep LED");.

The second bit of the mask is fairly common for NumLock, but I don't believe it is guaranteed.

Original answer: A good starting point is xev, available for about 20 years:

   xev

And you can decode key events via:

foobar (XKeyEvent *bar) {
   char dummy[20];
   KeySym key;
   KeySym keyKeypad;
   XLookupString(bar, dummy, sizeof dummy, &key, 0);
   keyKeypad = XKeycodeToKeysym(..., bar->keycode, NUMLOCK_Mask);
   if (IsKeypadKey(keyKeypad))
      ...;
   // ...
}