使用getche函數監聽鍵盤的例子:
- #include <stdio.h>
- #include <conio.h>
- int main(){
- char ch;
- int i = 0;
- //循環監聽,直到按Esc鍵退出
- while(ch = getch()){
- if(ch == 27){
- break;
- }else{
- printf("Number: %d\n", ++i);
- }
- }
- return 0;
- }
Number: 1 //按下任意鍵
Number: 2 //按下任意鍵
Number: 3
Number: 4
Number: 5 //按下Esc鍵
這段代碼雖然達到了監聽鍵盤的目的,但是每次都必須按下一個鍵才能執行getch后面的代碼,也就是說,getch后面的代碼被阻塞了。
阻塞式鍵盤監聽非常不方便,尤其是在游戲中,往往意味着用戶要不停按鍵游戲才能進行,所以一般采用非阻塞式鍵盤監聽。
使用
我們每按下一個鍵,都會將對應的字符放到鍵盤緩沖區,kbhit 函數會檢測緩沖區中是否有字符,如果有字符返回非0值,沒有返回0。但是kbhit不會讀取字符,字符仍然留在緩沖區。請看下面的例子:
- #include <stdio.h>
- #include <windows.h>
- #include <conio.h>
- int main(){
- char ch;
- int i = 0;
- //循環監聽,直到按Esc鍵退出
- while(1){
- if(kbhit()){
- ch = getch();
- if(ch == 27){
- break;
- }
- }
- printf("Number: %d\n", ++i);
- Sleep(1000); //暫停1秒
- }
- return 0;
- }
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5 //按下Esc鍵
每次循環,kbhit 會檢測用戶是否按下某個鍵(也就是檢測緩沖區中是否有字符),沒有的話繼續執行后面的語句,有的話就通過 getch 讀取,並判斷是否是 Esc,是的話就退出循環,否則繼續循環。
kbhit 之所以能夠實現非阻塞式監聽是因為它只檢測字符,而不要求輸入字符。