-->

Detecting keydown and keyup events on Linux C++ [d

2020-03-30 02:29发布

问题:

This question already has answers here:
Closed 7 years ago.

Possible Duplicate:
Access Keystrokes in C
Monitoring Keyboard keys in Ubuntu

I want to detect and time stamp every keydown and keyup event in a program (Yes, I mean keydown and keyup not just keypress) along with what key was pressed. I could do this by using an APi such as GTK, but I want to get as simple and low level as possible in order to avoid overhead from the libraries affecting the times as well as writing less code.

I have been googling this for a while and so far have found a ton of stuff about how to do it on Windows, which doesn't help me since I am using a Linux system, and how to detect a key press on Linux, but not keyup keydown.

Can anyone tell me what syscall, library, etc. I would need to use in order to capture the keydown and keyup events on a Linux system with a commandline program in C++? And if you have a link to a tutorial or a code example it would be most appreciated.

回答1:

You could read the raw device, I havn't tried this but this blog post looks promising: http://www.thelinuxdaily.com/2010/05/grab-raw-keyboard-input-from-event-device-node-devinputevent/

so essentially you're reading directly from /dev/input/*

You can verify this works by running sudo cat /dev/input/eventX where X is one of the event devices listed in that directory (one of them will be your keyboard.. I'm sure there is a good way of finding which one programatically, but you can quickly find out by looking in /dev/input/by-id/ or just reading from one of those symlinks directly.)


NOTE: This will get you keyboard input all the time, not just when your window is in focus.. (your program wouldn't even need to be running in an xterm, or even a pty for that matter).



回答2:

Realistically, you aren't going to be able to do this without a library. If you want something that has very little overhead, I would suggest ncurses. If you absolutely must do it without a library, look at how ncurses implements it. It will, of course, be very complicated.



回答3:

I would consider taking a look at OIS (Object Oriented Input System) library. It is quite easy to use, has a good OO design and it is cross-platform. For a tutorial and some code take a look at http://www.ogre3d.org/tikiwiki/tiki-index.php?page=Using+OIS.