0

Hey wassup? I need to know how to detect arrow keysand the escape key, and any help would be greatly appreciated, thanks!

3
Contributors
9
Replies
12
Views
8 Years
Discussion Span
Last Post by CodeBoy101
Featured Replies
  • Why don't you try running the program and pressing the enter key. The program will display the code for the key. Then you can put the key code as a case in the switch() just like what has been done for the other keys. This way you can find out … Read More

0

You can also use the functions from conio.h, kbhit() and getch(). up/down/left/right return 2 codes, while esc return 1 code.

if(kbhit()){
         int ch = 0 | getch();
         if(ch == 0xe0 && kbhit()){     // extended character (0xe0, xxx)
            ch = (ch<<8) | getch();     // get extended xharaxter info
            }
         switch(ch){
            case 0x1b:    cout << "ESC pressed" << endl;break;
            case 0xe048:    cout << "Up pressed" << endl;break;
            case 0xe050:    cout << "Down pressed" << endl;break;
            case 0xe04b:    cout << "Left pressed" << endl;break;
            case 0xe04d:    cout << "Right pressed" << endl;break;            
            default:    cout << "Some other key pressed " << hex << (int)(unsigned char)ch << " '" << (char)ch << "'" << endl;break;
            }
         cout << endl;
         }
0

>>You can also use the functions from conio.h,
Only if his compiler supports those functions. They are non-standard and only a few compilers support them.

0

Hey doug, thanks for your suggestion, I tried to create a program with the code you submitted, but the thing is, when I try to run the exe., the window opens, and then closes, just like that, so I was wondering, how would I use thins code in a program?
(^ _ ^) Thanx!

0

You'll probably want to run it in a loop - the code I gave only checks once for a keypress. so:

while(1){
   [ insert the keychecking code I posted here...]
   Sleep(1);   // don't use 100% cpu
   }
0

Thanks, it worked like a charm. I should have mentioned that I need the code for enter as well, but I suppose it would be wise to ask for the codes as many keys as possible. Thanks!!
(^ _ ^)

1

Why don't you try running the program and pressing the enter key. The program will display the code for the key. Then you can put the key code as a case in the switch() just like what has been done for the other keys. This way you can find out any key code you need.

Votes + Comments
Very helpful, this guy is a reason to be on Daniweb!
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.