Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to capture any key in X?

I am building an application for which I need to periodically get information about users keyboard. It is going to be user idle detection application. I have a fairly simple solution to periodically check if the mouse has been moved. But I can't figure any reasonable non root way to detect if the keyboard has been pressed.

I was thinking about registering a hook every timer timeout and on any key press to unregister it. So if there is no key press for a long time then my program will know if the user is idle.

Anyway, I couldn't find any global hooks for any key, including modifiers. Is there an easy way to do this? Or would someone have a better way to detect keyboard idleness?

Thanks

like image 736
David Polák Avatar asked Nov 05 '22 12:11

David Polák


1 Answers

After a lot of searching I found this:

bool kbdActivity(Display* display)  // checks for key presses
{
    XQueryKeymap(display, keymap);  // asks x server for current keymap
    for (int i=0; i<32; i++)        // for 0 to 32 (keymap size)
    {
        if (prevKeymap[i] != keymap[i])   // if previous keymap does not
        {                               // equal current keymap 
            XQueryKeymap(display, prevKeymap);  // ask for new keymap
            return true;                // exit with true
        }
    }
    return false;                   // no change == no activity
}

When I call it every 100-300ms it detects any pressed key anywhere in X.

like image 77
David Polák Avatar answered Nov 11 '22 03:11

David Polák