'X11: Detect general Mouse and Keyboard events

Is there a way to detect if the mouse has been moved ANYWHERE on the X Server or a keyboard event occured? I need to react on the user doing anything with the X11 input devices.

I only managed to detect events on my own window using GTK.

I am thankful for every information (it does not have to be full code, an entry point would be good enough!)



Solution 1:[1]

Yes, you can do this using the Xinput2 extension. A complete, but rather small, tool which does this for cursor events can be found here (unclutter-xfixes). As a disclaimer, I am the author of that tool.

Another good resource in tutorial form can be found here.

Using XInput2 has multiple benefits:

  • No need to constantly poll the position (resource efficient)
  • Does not interfere with / break applications like selecting mouse events on all windows would.

What you don't get easily using Xinput2 is the exact position (but you can query it when you need it), but my understanding is that you don't need it anyway.

Once you loaded the extension, which I won't show here, you can select all events like this:

XIEventMask masks[1];
unsigned char mask[(XI_LASTEVENT + 7)/8];

memset(mask, 0, sizeof(mask));
XISetMask(mask, XI_RawMotion);
XISetMask(mask, XI_RawButtonPress);
XISetMask(mask, XI_RawKeyPress);

masks[0].deviceid = XIAllMasterDevices;
masks[0].mask_len = sizeof(mask);
masks[0].mask = mask;

XISelectEvents(display, DefaultRootWindow(display), masks, 1);
XFlush(display);

In your event queue, you can now look for the corresponding events.

Solution 2:[2]

For modern X11 implementations, xinput --test-xi2 --root will display great detail about all X11 input events available on your root window. I use this in a shell script that needs to wait on any input event:

echo "DEBUG $(date) waiting on X event"
xinput --test-xi2 --root  | head -n 15 >/dev/null
echo "DEBUG $(date) got X event"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Ian D. Allen