C++:GetAsyncKeyState() 不会立即注册按键
C++: GetAsyncKeyState() does not register key press immediately
在我编写的程序中,当我按下 'escape' 键时,我希望它立即注册,即使是在睡眠期间。目前它在注册按键之前等到睡眠语句结束。休眠时间对程序来说很重要,所以不是随便加个暂停等待用户输入就可以了。
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;
}
编辑:澄清一下,睡眠的原因是我在一个时间间隔内重复执行一个动作。
您可以检查 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));
}
在我编写的程序中,当我按下 'escape' 键时,我希望它立即注册,即使是在睡眠期间。目前它在注册按键之前等到睡眠语句结束。休眠时间对程序来说很重要,所以不是随便加个暂停等待用户输入就可以了。
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;
}
编辑:澄清一下,睡眠的原因是我在一个时间间隔内重复执行一个动作。
您可以检查 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));
}