Pages

Saturday, October 6, 2012

Using the arrow keys in c++ using scan codes

As a programmer you may have been tempted to use the arrow keys to take input from the user, did you get frustrated and gave up because it was not as trivial as it should be?
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
Since the arrow keys fall under the extended scancode category. Lets see what code is generated when an arrow key is pressed.

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

Scancodes c++ and the getch function

The getch function gets a single character from the console, since extended scan codes, especially the arrow keys generate two bytes, you can already judge why we'd need two calls to getch(), the first call gets the code 224 and the next one gets the actual code for the key pressed. The rest is plain c++ switch statements. Enjoy your programming :)

1 comment:

  1. Amazing explanation!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

    ReplyDelete