0

在我编写的程序中,当我按下“退出”键时,我希望它立即注册,即使在睡眠期间也是如此。目前,它会等到 sleep 语句结束后才注册按键。睡眠时间对程序很重要,因此不仅仅是添加暂停和等待用户输入的问题。

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;
}

编辑:澄清一下,睡眠的原因是我在一个时间间隔内重复执行一个动作。

4

1 回答 1

1

您可以检查是否经过了 10 秒,而不是睡 10 秒,然后执行此时需要做的任何事情。这样循环会不断检查按键。

#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));
}
于 2017-08-04T02:27:49.730 回答