No GUI is complete without a strong user interface and to interact with the
user, a curses program should be sensitive to key presses or the mouse actions
done by the user. Let's deal with the keys first.
As you have seen in almost all of the above examples, it's very easy to get key
input from the user. A simple way of getting key presses is to use
getch() function. The cbreak mode should be
enabled to read keys when you are interested in reading individual key hits
rather than complete lines of text (which usually end with a carriage return).
keypad should be enabled to get the Functions keys, arrow keys etc. See the
initialization section for details.
getch() returns an integer corresponding to the
key pressed. If it is a normal character, the integer value will be equivalent
to the character. Otherwise it returns a number which can be matched with the
constants defined in curses.h. For example if
the user presses F1, the integer returned is 265. This can be checked using the
macro KEY_F() defined in curses.h. This makes reading keys portable and easy to
manage.
For example, if you call getch() like this
int ch;
ch = getch();
getch() will wait for the user to press a key, (unless you specified a timeout)
and when user presses a key, the corresponding integer is returned. Then you can
check the value returned with the constants defined in curses.h to match against
the keys you want.
The following code piece will do that job.
if(ch == KEY_LEFT)
printw("Left arrow is pressed\n");
Let's write a small program which creates a menu which can be navigated by up
and down arrows.