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

Recommended Answers

All 9 Replies

If you are writing a console program then see these console functions. Not immediately sure which one(s) you need to use. You might also look through some of these links

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;
         }

>>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.

Dev-c++ supports these functions

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!

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
   }

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!!
(^ _ ^)

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.

commented: Very helpful, this guy is a reason to be on Daniweb! +1

Thanks a lot!!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.