This item was added on: 2003/03/22
This is system dependent as the most portable solution relies on the keyboard codes that map to the directional keys. Next you need a raw input function that takes a single character such as getch
(a UNIX implementation is given later in this FAQ "How can I get input without having the user hit [Enter]?"). To get the correct codes for your system, you must search by way of a simple input function:
int get_code ( void )
{
int ch = getch();
if ( ch == 0 || ch == 224 )
ch = 256 + getch();
return ch;
}
Then build a list of key code constants so that they can be easily changed if the program is ported:
enum
{
KEY_UP = 256 + 72,
KEY_DOWN = 256 + 80,
KEY_LEFT = 256 + 75,
KEY_RIGHT = 256 + 77
};
Then it is only a matter of testing for those codes in your program and performing the correct action:
#include <stdio.h>
#include <conio.h>
enum
{
KEY_ESC = 27,
ARROW_UP = 256 + 72,
ARROW_DOWN = 256 + 80,
ARROW_LEFT = 256 + 75,
ARROW_RIGHT = 256 + 77
};
static int get_code ( void )
{
int ch = getch();
if ( ch == 0 || ch == 224 )
ch = 256 + getch();
return ch;
}
int main ( void )
{
int ch;
while ( ( ch = get_code() ) != KEY_ESC ) {
switch ( ch ) {
case ARROW_UP:
printf ( "UP\n" );
break;
case ARROW_DOWN:
printf ( "DOWN\n" );
break;
case ARROW_LEFT:
printf ( "LEFT\n" );
break;
case ARROW_RIGHT:
printf ( "RIGHT\n" );
break;
}
}
return 0;
}
An alternative solution to this problem is the Win32 API:
#include <stdio.h>
#include <limits.h>
#include <stdlib.h>
#include <windows.h>
int main ( void )
{
short esc = 0;
while ( !esc ) {
esc = GetAsyncKeyState ( VK_ESCAPE );
if ( GetAsyncKeyState ( VK_UP ) & SHRT_MAX )
puts ( "Up arrow is pressed" );
else if ( GetAsyncKeyState ( VK_DOWN ) & SHRT_MAX )
puts ( "Down arrow is pressed" );
else if ( GetAsyncKeyState ( VK_LEFT ) & SHRT_MAX )
puts ( "Left arrow is pressed" );
else if ( GetAsyncKeyState ( VK_RIGHT ) & SHRT_MAX )
puts ( "Right arrow is pressed" );
}
return EXIT_SUCCESS;
}
Or the curses library:
#include <curses.h>
int main ( void )
{
initscr();
noecho();
keypad ( stdscr, TRUE );
while ( 1 )
{
switch ( getch() )
{
case KEY_UP:
printw ( "UP\n" );
break;
case KEY_DOWN:
printw ( "DOWN\n" );
break;
case KEY_LEFT:
printw ( "LEFT\n" );
break;
case KEY_RIGHT:
printw ( "RIGHT\n" );
break;
}
refresh();
}
endwin();
return 0;
}
Credit: Prelude