In the program I am writing when I hit the 'escape' key, I want it to exit immediately. Currently it waits until the end of the sleep statement before registering. In the program that I am writing, sleep statements can be several minutes long, and I do not want to wait until the end for key presses to be registered. Thank you in advance!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
int main()
{
bool ESCAPE = false;
while (!ESCAPE) {
// Stop program when Escape is pressed
if (GetAsyncKeyState(VK_ESCAPE)) {
cout << "Exit triggered" << endl;
ESCAPE = true;
}
Sleep(10000);
}
system("PAUSE");
return 0;
}
EDIT: To clarify, the sleep is because I am performing an action after a given period of time
if (GetAsyncKeyState(VK_ESCAPE))
{
cout << "\nExit triggered" << endl; // <--- You may want the "\n" for better readability.
ESCAPE = true;
continue; // <--- Continues to the next while condition.
break; // <--- will leave the while loop.
or
exit (1); // <--- Will leave the program.
}
Not sure if the "Sleep(10000);" is worth keeping here?
Here the escape key is tested 4 times per second during the delay period. That's a compromise, you could change that to say 50 times per second if you like, to make it a bit more responsive if essential. Though if the required sleep time is several minutes, a response within a second or two might suffice.