GetAsyncKeyState() during a Sleep() does not register immediately

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
Last edited on
Hello gunman353,

You could try this:

1
2
3
4
5
6
7
8
9
	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?

Hope that helps,

Andy
The sleep time is important for my program, as the user needs to define the time between repeating events.
as the user needs to define the time between repeating events.
Consider using timer for this:

https://msdn.microsoft.com/en-us/library/windows/desktop/ms644906(v=vs.85).aspx
A rather clunky approach using Sleep().

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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
#include <windows.h>

using std::cout;
using std::endl;

bool testEscape(unsigned millisec)
{
    bool result = false;
    unsigned delay = 250;

    for (unsigned i=0; !result && i<millisec; i += delay)
    {
        result = GetAsyncKeyState(VK_ESCAPE);
        Sleep(delay);
    }
        
    return result;      
}

int main()
{
    cout << "start\n";
    
    bool escape = false;

    while (!escape) 
    {
        cout << ".";

        escape = testEscape(10000);
        if (escape)
            cout << "Exit triggered" << endl;
        
    }

    cout << "done\n";
    system("pause");
    return 0;
}
Last edited on
Topic archived. No new replies allowed.