c++sleepkeypressgetasync

C++: GetAsyncKeyState() does not register key press immediately


In the program I am writing when I hit the 'escape' key, I want it to register immediately, even during the sleep period. Currently it waits until the end of the sleep statement before registering the key press. The sleep time is important to the program, so it is not a matter of just adding a pause and waiting on user input.

int main()
{

    bool ESCAPE = false; // program ends when true

    while (!ESCAPE) {
        // Stop program when Escape is pressed
        if (GetAsyncKeyState(VK_ESCAPE)) {
            cout << "Exit triggered" << endl;
            ESCAPE = true;
            break;
        }

        Sleep(10000);
    }
    system("PAUSE");
    return 0;
}

EDIT: To clarify, the reason for the sleep is that I am performing an action repeatedly on a time interval.


Solution

  • Instead of sleeping for 10 seconds, you can check if 10 seconds is passed, and do whatever needs to be done at that point. This way the loop is checking constantly for a keypress.

    #include <chrono>
    ...
    auto time_between_work_periods = std::chrono::seconds(10);
    auto next_work_period = std::chrono::steady_clock::now() + time_between_work_periods;
    
    while (!ESCAPE) {
        // Stop program when Escape is pressed
        if (GetAsyncKeyState(VK_ESCAPE)) {
            std::cout << "Exit triggered" << std::endl;
            ESCAPE = true;
            break;
        }
    
        if (std::chrono::steady_clock::now() > next_work_period) {
            // do some work
            next_work_period += time_between_work_periods;
        }
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
    }