Detecting keypress in Visual C++
August 7, 2008
Jeez, I couldn’t believe how many people on the net have the same problem; detecting a key press from Visual C++ without echoing the same to the screen (ie: console).
I had this exact requirement today since I was trying to (re)write “Space Invaders” game to test the C++ console mode skills.
All I wanted to do was to detect the arrow keys and throw a message identifying the keys. But digging MSDN never helped me, it was overloaded with ’solutions’
After few experiments I figured the way to go forward is to use _kbhit from conio.h library. Remember conio.h is coming from ‘C’ not ‘C++’ so you got to use the ‘.h’ with it. Also note that usual keys return one character but special keys (function keys, arrow keys etc…) returns two characters. These are called ’scan codes’. Go here or here for more info; and if you are into assembly or electronics, here’s the text from the famous PC assembly language book, “Art of Assembly”. This note from MSDN explains the getch() function.
I wrote and tested this in Visual Studio 2005. Here’s the code:
-
#include "stdafx.h"
-
#include <iostream>
-
#include <conio.h>
-
-
using namespace std;
-
-
int main()
-
{
-
char ch;
-
-
cout << "key press detector : use ‘z’, ‘x’ or arrow keys" << endl;
-
cout << "press CTRL+C to exit. \n\n" << endl;
-
-
while(true) // this is the main loop
-
{
-
if (_kbhit())
-
{
-
// in case of a key is hit, do these
-
ch = getch();
-
switch(ch)
-
{
-
case ‘z’ :
-
cout << "you pressed z" << endl;
-
break;
-
-
case ‘x’ :
-
cout << "you pressed x" << endl;
-
break;
-
-
case ‘\0H’ :
-
cout << "you pressed up arrow key" << endl;
-
break;
-
-
case ‘\0P’ :
-
cout << "you pressed down arrow key" << endl;
-
break;
-
-
case ‘\0M’ :
-
cout << "you pressed right arrow key" << endl;
-
break;
-
-
case ‘\0K’ :
-
cout << "you pressed left arrow key" << endl;
-
break;
-
}
-
//below line displays the key code
-
//exit (1); // in this example, it is "exit the program!"
-
}
-
}
-
}
Here’s the source code and EXE for testing.
Allegro, a cool game development kit for DOS etc…
And a good Allegro example site
Rate this article (164 views)
Print This Post
Email This Post
2 Responses to “Detecting keypress in Visual C++”
Got something to say?


















AlexFM
on August 7th, 2008 11:55 amAzmeer, you save my day ! a very big thank you…..
This is exactly what I was looking for.
RanjitW
on August 12th, 2008 6:52 amHi, thanks for the code. Do you need to use _kbhit at all? since you use getch() anyway?