2017-08-04 67 views
0

在我正在编写的程序中,当我点击'转义'键时,即使在睡眠期间,我也希望它立即注册。目前它在注册按键之前一直等待到睡眠声明结束。睡眠时间对于程序来说很重要,所以它不是仅仅添加暂停和等待用户输入的问题。C++:GetAsyncKeyState()不立即注册按键

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

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

+0

你为什么睡10秒?是因为你想每10秒执行一次特定动作吗? –

+0

是的,我每10秒钟执行一次动作 – Grehgous

+0

@Grehgous然后用一个定时器代替,特别是一个等待定时器。 –

回答

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)); 
} 
+1

该循环将继续占用CPU周期,从而导致CPU使用率过高。为什么不插入特定持续时间的std :: this_thread :: sleep_for? – Asesh

+0

@Asesh在每次检查now和next_work_period之前,std :: this_thread :: sleep_for的好处是什么,而不是仅仅调用sleep()? – Grehgous

+1

@Grehgous如果你使用第一个,那么你的代码将是可移植的,睡眠是一个Windows API,但如果你只是针对Windows,那么你可以使用睡眠 – Asesh