Well it is a piece of cake but to eat it you have to earn it.
Wait no further....
For those in a hurry here is the code
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
int c;
while (1)
{
c = getch(); // first call gets the 0xE0 byte or decimal 224
switch(c) // lets just waste the value
{
case 0:
case 224:
switch (getch()) //Here the actual code for the key is got
{
case 72: cout << "up arrow\n"; break;
case 75: cout << "left arrow\n"; break;
case 77: cout << "right arrow\n"; break;
case 80: cout << "down arrow\n"; break;
default: cout << "extended key " << c << "\n";
}
}
}
return 0;
}
Lets De-magicify
And here is the treat for the geeks.Lets examine the code step by step. Before diving into details lets have a look at the background. Any key pressed from the key board generates a unique code (think of it as a number stored as a HEX value), this code is known as Scancode Generally each code is one byte in size but some keys (keys with special functions) generate two or more bytes and this code is referred to as extended Scancodes
The following keys fall under the extended category
- Arrow keypad
- Home keypad
- Right Alt
- Right Ctrl
- keyboards with the arrow pad, home pad and number pad
If an arrow key is pressed it generates two bytes, one the code for the key pressed prefixed with an 0xE0 or decimal 224 (scan code for left shift release) on most systems. The corresponding scan codes for the keys are
- Up 72
- Down 80
- Left 75
- Right 77
Amazing explanation!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
ReplyDelete