C語言非阻塞式鍵盤監聽


監聽鍵盤可以使用C語言的字符輸入函數,例如 getchar、getch、getche 等,

使用getche函數監聽鍵盤的例子:
   
   
   
           
  1. #include <stdio.h>
  2. #include <conio.h>
  3. int main(){
  4. char ch;
  5. int i = 0;
  6. //循環監聽,直到按Esc鍵退出
  7. while(ch = getch()){
  8. if(ch == 27){
  9. break;
  10. }else{
  11. printf("Number: %d\n", ++i);
  12. }
  13. }
  14. return 0;
  15. }
運行結果:
Number: 1  //按下任意鍵
Number: 2  //按下任意鍵
Number: 3
Number: 4
Number: 5  //按下Esc鍵

這段代碼雖然達到了監聽鍵盤的目的,但是每次都必須按下一個鍵才能執行getch后面的代碼,也就是說,getch后面的代碼被阻塞了。

阻塞式鍵盤監聽非常不方便,尤其是在游戲中,往往意味着用戶要不停按鍵游戲才能進行,所以一般采用非阻塞式鍵盤監聽。

使用 de >conio.h de> 頭文件中的 de >kbhit de> 函數可以實現非阻塞式鍵盤監聽。

我們每按下一個鍵,都會將對應的字符放到鍵盤緩沖區,kbhit 函數會檢測緩沖區中是否有字符,如果有字符返回非0值,沒有返回0。但是kbhit不會讀取字符,字符仍然留在緩沖區。請看下面的例子:
     
     
     
             
  1. #include <stdio.h>
  2. #include <windows.h>
  3. #include <conio.h>
  4. int main(){
  5. char ch;
  6. int i = 0;
  7. //循環監聽,直到按Esc鍵退出
  8. while(1){
  9. if(kbhit()){
  10. ch = getch();
  11. if(ch == 27){
  12. break;
  13. }
  14. }
  15. printf("Number: %d\n", ++i);
  16. Sleep(1000); //暫停1秒
  17. }
  18. return 0;
  19. }
運行結果:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5  //按下Esc鍵

每次循環,kbhit 會檢測用戶是否按下某個鍵(也就是檢測緩沖區中是否有字符),沒有的話繼續執行后面的語句,有的話就通過 getch 讀取,並判斷是否是 Esc,是的話就退出循環,否則繼續循環。

kbhit 之所以能夠實現非阻塞式監聽是因為它只檢測字符,而不要求輸入字符。

來源:python腳本自動遷移


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM