Keyboard handler in C
In C, how can I write a program that tells me which keys are pressed? For example, it should output
You pressed F1 key
You pressed ESC key
You released F1 key
to the Linux console and terminate the program if, for example, the F1 and q keys are pressed.
I tried
#include <curses.h> // required
int r,c, // current row and column (upper-left is (0,0))
nrows, // number of rows in window
ncols; // number of columns in window
void draw(char dc)
{ move(r,c); // curses call to move cursor to row r, column c
delch(); insch(dc); // curses calls to replace character under cursor by dc
refresh(); // curses call to update screen
r++; // go to next row
// check for need to shift right or wrap around
if (r == nrows) {
r = 0;
c++;
if (c == ncols) c = 0;
}
}
main()
{ int i; char d;
WINDOW *wnd;
wnd = initscr(); // curses call to initialize window
cbreak(); // curses call to set no waiting for Enter key
noecho(); // curses call to set no echoing
getmaxyx(wnd,nrows,ncols); // curses call to find size of window
clear(); // curses call to clear screen, send cursor to position (0,0)
refresh(); // curses call to implement all changes since last refresh
r = 0; c = 0;
while (1) {
d = getch(); // curses call to input from keyboard
if (d == 'q') break; // quit?
draw(d); // draw the character
}
endwin(); // curses call to restore the original window and leave
}
but it has problems like recognizing shift and valgrind keys
==11693== still reachable: 59,676 bytes in 97 blocks
source to share
First, note that this is not a C question; the answer depends on Linux. The C language does not offer a keyboard API.
To detect both keystrokes and releases, you have to go deeper than
- the behavior of a Linux terminal driver default (the so-called "cooked" mode), which allows you to read the characters in the string at a time, using functions such as
getc
andscanf
, as well as - a so-called "raw" mode driver that delivers to your application every keystroke used by modern editors and shells, and is provided by the curses API.
You do this by looking at the input events. See header input.h , related article and usage example . Note that with this API, you get the bottom level information: key scan codes instead of ASCII or Unicode codes, and key presses ( EV_KEY
), key-up ( EV_REL
) events , not key presses.
source to share
You can easily detect the "classic" input (letters, numbers and symbols) with a simple scanf
/ printf
(you should get your input code in Unicode , UTF-8 encoded).
For "special" keys: look there .
There seems to be no standard way to do this, but some links are being passed on to a third party library which will hopefully help.
source to share