I am writing a command line interface for a console program on Linux. I want to be able to use keys like arrows in it. So to capture the codes, I am using this simple program:
int main()
{
int c = 0;
while (c != 3) { // ctrl-c
c = getchar();
printf("%d\n", c);
}
}
Doing this I had problems capturing the HOME key. On one computer I got the sequence "27 91 72", on another I got "27 79 72" and on a third I got "27 91 49 126".
I am not sure why I am getting so different codes on HOME and END keys (Arrows and F1-F12 keys gave the same sequence on the three computers).
Is there a standard way to get this keys, or some sort of configuration that would give me the same sequence on all machines?
You may use the curses framework.
When using curses it is quiet easy to get special key presses. But the downside is you have to pull in the whole curses library at link time (e.g. with gcc -lcurses) and you have to use all the curses function inside an initialized curses screen.
#include <stdio.h>
#include <curses.h>
int main()
{
int c = 0;
initscr();
keypad(stdscr, 1);
c = getch();
endwin();
printf("0x%04x\n", c);
printf("0x%04x\n", KEY_HOME);
}
This will initialize the standard screen (stdscr), enable the keypad in it and get a key-press using getch() and close the stdscr again retoring the tty modes.
You can also check if a special key is supported in your current terminal using the has_key() function.
That is the easy way..