According to documentation, try this:
int key;
key = _getch();
if( key == 0xE0 ) // 224
{
key = _getch( );
}
printf( "%d", key );
You should distinguish between Left Arrow and 'K', for example, which returns 75 too.
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Why is it printing 224 an integer value for arrows key [left,right,top and bottom] in this code,
int main()
{
int key;
key = _getch();
printf("%d", key);
return 0;
}
while the integer value for arrows keys are 72,80,75,77. It is printing right in below code :-
void draw();
void gotoxy(int, int);
i = 10, j = 10;
int main()
{
printf("Press alphabet e in small case to exit the program....\n");
gotoxy(i, j);
draw();
return 0;
}
void draw()
{
int key;
while (1)
{
key = _getch();
switch (key)
{
case 75:
printf("%d",key);
i--;
break;
case 77:
i++;
break;
case 72:
j--;
break;
case 80:
j++;
break;
case 'e':
gotoxy(10, 70);
exit(0);
}
gotoxy(i, j);
printf("*");
}
}
void gotoxy(int row, int col)
{
HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
COORD position = {row,col };
SetConsoleCursorPosition(h, position);
}
According to documentation, try this:
int key;
key = _getch();
if( key == 0xE0 ) // 224
{
key = _getch( );
}
printf( "%d", key );
You should distinguish between Left Arrow and 'K', for example, which returns 75 too.
Why is it printing 224 an integer value for arrows key ...
while ... It is printing right in below code
Extended keys are preceded by a prefix byte, sometimes
called an "escape scancode". So getting the value for the
key itself requires two "_getch" executions, as illustrated
in the example from Viorel.
About Keyboard Input
https://learn.microsoft.com/en-us/windows/win32/inputdev/about-keyboard-input
Extended-Key Flag
"The extended-key flag indicates whether the keystroke message
originated from one of the additional keys on the enhanced
keyboard. The extended keys consist of the ALT and CTRL keys
on the right-hand side of the keyboard; the INS, DEL, HOME,
END, PAGE UP, PAGE DOWN, and arrow keys in the clusters to
the left of the numeric keypad; the NUM LOCK key; the BREAK
(CTRL+PAUSE) key; the PRINT SCRN key; and the divide (/) and
ENTER keys in the numeric keypad. The extended-key flag is
set if the key is an extended key.
If specified, the scan code was preceded by a prefix byte
having the value 0xE0 (224)."
Also see:
Keyboard scancodes
https://www.win.tue.nl/~aeb/linux/kbd/scancodes-1.html
1.3 Escape scancodes
"The codes e0 and e1 introduce scancode sequences, and are not
usually used as isolated scancodes themselves ..."
1.5 Escaped scancodes
See table.
Your second code sample "works" because of the while(1)
loop. When the escape code prefix 0xe0 is read no match
is found in the switch statement. But on the next iteration
of the loop the _getch reads the unique scan code for that
extended key. If you step through your code in the debugger
you should see what is happening.