How to monitor keyboard events from X11
embedded, linux
Solution
The correct way for doing that is using Xlib. Using this library you can write code like this:
while (1) {
XNextEvent(display, &report);
switch (report.type) {
case KeyPress:
if (XLookupKeysym(&report.xkey, 0) == XK_space) {
fprintf (stdout, "The space bar was pressed.\n");
}
break;
}
}
// This event loop is rather simple. It only checks for an expose event.
// XNextEvent waits for an event to occur. You can use other methods to get events,
// which are documented in the manual page for XNextEvent.
// Now you will learn how to check if an event is a certain key being pressed.
// The first step is to put case KeyPress: in your switch for report.type.
// Place it in a similar manner as case Expose.
Also you could use poll or select on the special device file that is mapped to your keyboard. In my case is `/dev/input/event1`.
If you have doubts about what's the special file mapped to your keyborad, read the file `/var/log/Xorg.0.log` (search for the word `keyboard`).
Here you have another link of interest: Linux keyboard event capturing /dev/inputX
Problem
I know there has been a few of these, but a lot of the answers always to have a lot of buts, ifs, and you shouldn't do that. What I'm trying to do is have a background program that can monitor the keyboard events from `X11`. This is on an embedded device, and it will have a main app basically running in something like a kiosk mode. We want to have a background app that manages a few things, and probably a back doors hook. But this app generally will not have focus. I can't use the main app, because its partially there for a fail safe if the main app ever fails, or to do some dev type things to bypass the main app. The best question I found is a few years old, so I'm not sure how up to date it is. This was extremely easy to do with windows. X KeyPress/Release events capturing irrespective of Window in focus