Search code examples
keyboardcinterruptevents

Key pressed and key released interrupts in C


Is there a way to catch the KEY PRESSED and KEY RELEASED events in while (1) loop in simple C program on Linux running from a terminal window.

kbhit() will return true if a key was pressed, getch() returns the character that was pressed.

How do I catch the RELEASE event?


Solution

  • You cannot do this in a portable manner. Terminals (and emulators of those such as xterm) give you only the key that was pressed, not the release events. Graphical user interfaces often provide the ability to receive separate press- and release-events.

    Terminal emulators running in a graphical environment compose those events into individual characters. As read in the graphical environment, those are key symbols, which may contain characters. In addition to the press- and release-events for the key events themselves, you can have modifiers such as shift-, control- and meta-modifiers which are separate events. If you run xev, you can see these separate events.

    After composing these events into a character, the terminal emulator may send it to your application as a series of data bytes, e.g., in UTF-8 encoding. When you use getch(), the ncurses library reads those bytes, and puts it together again into a character. In between those two (the terminal emulator and application) are the pseudo-terminal and its translation, which both terminal emulator and application must manipulate.

    If you are not running in a graphical environment, there are (not always) other ways than graphical applications such as xev which can read directly the key press/release events. The Linux console supports that. See for example the links cited in Receiving key press and key release events in Linux terminal applications?