Detect Escape Key pressed

May 11, 2012 at 9:10am
Hi,

I'm writing a program and required to output "escape pressed" when escape key is pressed when the program is running. How would I do this?

Note: I'm still new to C++

Cheers
May 11, 2012 at 5:36pm
Back in my days of Turbo Pascal 6 I once created a small program to reveal the key codes of all keys, including function keys, escape keys, arrow keys. I imagine you can do that too in C++. I think you can use getch() from ... the dontremembertheheader.h (hehe, I think it is stdio.h), or see if you can use std::cin.get() from the STL (#include <iostream>). There are other libraries for console input/output too, if you care to check them out.

Basically you use those functions in a loop and you print the code value on screen and voilá! I think the ESC key is code 27.

BTW, all that for a console application. If not a console application, I can only provide guidance for a Windows application.

Good luck!
May 11, 2012 at 7:45pm
Who is requiring you to detect the Esc key?
What library are you using? (conio.h?)
May 12, 2012 at 1:58am
Thanks webJose, I'll play around with it.

Its an assignment, so while the program is running the tester will randomly press the escape key.
May 12, 2012 at 2:14am
To handle ESC key inside your window procedure inser this case statement:
1
2
3
4
5
6
case WM_CHAR:
	if (wParam == VK_ESCAPE)
	{
		// handle escape key pressed here
	}
	return 0;

May 12, 2012 at 2:30am
1
2
3
4
5
6
7
8
9
   #include <windows.h>


 if(GetAsyncKeyState(VK_ESCAPE))
    {
        cout << "ESCAPE-PRESSED" << endl;
        Sleep(1000);
        return 0;
    }


Would this work?
May 12, 2012 at 2:37am
Yeah I think that should work too since GetAsyncKeyState take virtual key code.

EDIT:
Assuming you're running some kind of message loop of course :D
Last edited on May 12, 2012 at 2:53am
May 12, 2012 at 2:59am
Ah ok no wonder it didn't work, would you kindly give me a hand with that? :)
May 12, 2012 at 3:15am
Ah ok no wonder it didn't work


Hey amigo, actually it works just fine:

an silly example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <Windows.h>
#include <iostream>

int main()
{
	while(true)
	{
		if (GetAsyncKeyState(VK_ESCAPE))
		{
			std::cout << "DUDE! You've pressed the escape key";
			std::cin.ignore();
		}
	}
	return 0;
}
May 12, 2012 at 3:35am
Thanks for the help codekiddy
Topic archived. No new replies allowed.