Search code examples
linuxopenglinputxlib

Xlib keyboard polling


I'm working on a multi-platform OpenGL application, for which I'm using Xlib under Linux. I understand that Xlib input handling is strongly event-based, but my program already does its own event handling, and I'd much rather be able to poll the xserver for any keys which were pressed or raised under the active window since the last poll.

If I have to use event-based input handling under X, I'd have to do the same for other platforms, while rewriting a lot of code, since the event methods are so different from one platform to another. Polling would really simplify things for me, but I'm afraid there would be substantial overhead with something like this, and I haven't even been able to get information on how it should be done. I've thought of checking the /dev/input/eventX node directly, but that would probably make things more complicated, rather than simplifying.

What I really want to know is how to efficiently poll the keyboard state on Linux systems. Am I wasting my time with Xlib, and should I consider other techniques or libraries?


Solution

  • To efficiently poll, I usually use select (on ConnectionNumber), to wait until something happens on the connection to X and then while XPending I use XNextEvent to grab stuff. Do not call XNextEvent unless XPending or else it will block.

    Conveniently, select provides a timeout mechanism, so you can also stop waiting periodically to do something else (like drawing) quite easily.