Total Pageviews

Saturday, May 7, 2011

Read Arrow Keys in C++


Hi guys.
I would like to write a program in C++ ,doing something after pressing arrow keys.at first i decided to test reading arrow keys.i wrote a simple program that after pressing arrow keys prints in console screen which one of arrow keys is pressed.for writing this prog i require to find out Ascii values of this 4 keys.therefore i wrote a program print Ascii value of a keyboard key when i press that key.after running this program i find out this value is 3 byte.in my OS (Ubuntu 10.10) this 3 value is 27 , 91 , and 3rd part for UP key ,DOWN key ,RIGHT key ,LEFT key is consecutively  65,66,67 and 68.i expect this prog runs at Windows OS successfully ,because i expect this values be the same of Ubuntu in Windows OS.in Windows this prog is unusable and after discovering Ascii codes of my arrow keys in Windows (that is 2 byte 0x0H) i wrote another special prog for Windows.
I would like to write a portable program ,which can use in different type of OS?what's the solution?why ascii values are different in operating systems?
At the following you can see this progs ,in Ubuntu and also in Windows.

Sincerely.
Kaveh Shahhosseini 1/May/2011

//========================
//this progs wrote in C programming language.
//Ubuntu...used only 65,66,67,68 values instead of "27,91,65" , "27,91,66" ...
#include <stdio.h>
//--------------------------
int main()
{
    char ch;
    do{
        ch=getchar();
         if(ch==65)
            printf("You pressed UP key\n");
         else if(ch==66)
            printf("You pressed DOWN key\n");
         else if(ch==67)
            printf("You pressed RIGHT key\n");
         else if(ch==68)
            printf("You pressed LEFT key\n");



    }while(ch!='e');
 return 0;
}
//======================
//Windows...
#include <stdio.h>
#include <conio.h>
using namespace::std;
//-----------------------------
int main()
{
      char ch;
  do{

        ch=getch();
        if(ch!='\0')
        {
          ch=getch();
          if(ch=='H')
              printf("UP\n");
                 else    if(ch=='P')
              printf("DOWN\n");
                   else    if(ch=='M')
              printf("RIGHT\n");
                     else   if(ch=='K')
              printf("LEFT\n");
        }
  }while(ch!='e');

    return 0;
}
//====================

No comments:

Post a Comment