I am writing a small program in Visual Studio 11 (beta) that a console mfc app. I have never programmed for this environment before and I am trying to figure out how to detect the Escape-key press in the console. I have looked extensively at online resources and tried many different things can't figure it out.
Here is what I was trying to see if I could get it to work.
printf("Press Escape to exit.");
bool maxReached = true;
while (maxReached)
{
if(WM_COMMAND == IDCANCEL) // Tried many different things here, like WM_KEYDOWN == VK_ESCAPE. no luck
{
maxReached = false;
}
}
exit(-1);
Any help would be much appreciated.
Kamal
You can detect using
if (getch() == 0x1B) // escape detected
{
maxReached = false;
}
You can always install a keyboard hook and check for the ESC key being pressed.
Here's how:
First, install the hook
HHOOK hhkLowLevelKybd;
HINSTANCE hInstance = GetModuleHandle(NULL);
// Install the low-level keyboard hook
hhkLowLevelKybd = SetWindowsHookEx(WH_KEYBOARD_LL,
LowLevelKeyboardProc,
hInstance,
NULL );
Next, have LowLevelKeyboardProc execute your routines in response to the ESC keyup:
_declspec(dllexport) LRESULT CALLBACK LowLevelKeyboardProc( int nCode, WPARAM wParam, LPARAM lParam)
{
if (nCode == HC_ACTION)
{
PKBDLLHOOKSTRUCT p = ( PKBDLLHOOKSTRUCT ) lParam;
switch (wParam)
{
case WM_KEYUP:
case WM_SYSKEYUP:
switch (p->vkCode)
{
case 0x1B: //OR VK_ESCAPE
maxReached = false;
break;
default:
break;
}
break;
default:
break;
}
}
return(CallNextHookEx( NULL, nCode, wParam, lParam ));
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.