I'm writing a programm that's using getch()
to scan for arrow keys. My code so far is:
switch(getch()) {
case 65: // key up
break;
case 66: // key down
break;
case 67: // key right
break;
case 68: // key left
break;
}
Problem is that when I press 'A'
, 'B'
, 'C'
or 'D'
the code will also executed, because 65
is the decimal code for 'A'
, etc...
Is there a way to check for an arrow key without call others?
Thanks!
By pressing one arrow key
getch
will push three values into the buffer:'\033'
'['
'A'
,'B'
,'C'
or'D'
So the code will be something like this:
for a solution that uses
ncurses
with working code and initialization of ncurses see getchar() returns the same value (27) for up and down arrow keyshow about trying this?
(if you can't understand why there is 224, then try running this code: )
but I don't know why it's 224. can you write down a comment if you know why?
The
keypad
will allow the keyboard of the user's terminal to allow for function keys to be interpreted as a single value (i.e. no escape sequence).As stated in the man page:
getch () function returns two keycodes for arrow keys (and some other special keys), as mentioned in the comment by FatalError. It returns either 0 (0x00) or 224 (0xE0) first, and then returns a code identifying the key that was pressed.
For the arrow keys, it returns 224 first followed by 72 (up), 80 (down), 75 (left) and 77 (right). If the num-pad arrow keys (with NumLock off) are pressed, getch () returns 0 first instead of 224.
Please note that getch () is not standardized in any way, and these codes might vary from compiler to compiler. These codes are returned by MinGW and Visual C++ on Windows.
A handy program to see the action of getch () for various keys is:
This works for MinGW and Visual C++. These compilers use the name _getch () instead of getch () to indicate that it is a non-standard function.
So, you may do something like: