'How to disable the on key press exiting
I like to code and am trying a new language. C++ is new to me but I have 1 question. How do I change the fact that when I build and run my C++ console app it asks me to press any key to quit but I only want it to quit when I press the ESC key. How do I disable the thing that makes me press any key to quit? I am using Visual Studio 2022 with the C++ Console Application template.
Here is my code:
#include <iostream>
#include <winuser.h>
#include <cstdlib>
using namespace std;
void main () {
char message[21] = "Hello There!";
cout << message;
if (GetAsyncKeyState(VK_ESCAPE))
{
exit(0);
}
}
Solution 1:[1]
Your problem is that GetAsyncKeyState() returns immediately. You are asking it to see if the ESC key is currently pressed. It returns 0 or 1, then the code carries on, so you exit from main() any way. What you want is this:
void main() {
char message[21] = "Hello There!";
cout << message;
while (!GetAsyncKeyState(VK_ESCAPE))
{
Sleep(500);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Remy Lebeau |
