2017-08-04 61 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