clinuxkeyboardmousex11

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

  • 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:

    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.