检测某个键是否按下,-非阻塞模式,处理键盘字符事件C语言
通常我们的很多程序都是一个while循环, 想在按下某个按键时退出.如何检测这个键按下?
通常有两种方式来做
一 利用阻塞函数来做.
利用阻塞函数检测按键, 又不想让主线程阻塞, 就可以另开一个线程,在线程里面检测按键是否按下. 好像老吉在linux下的版本
就是这样实现的. 通过一个全局变量和主线程通信.
二 利用非阻塞函数来做.
版本一:
1. /* KBHIT.C: This program loops until the user
2. * presses a key. If _kbhit returns nonzero, a
3. * keystroke is waiting in the buffer. The program
4. * can call _getch or _getche to get the keystroke.
5. */
6. //
7. #include 8. #include 9. void main( void ) 10. { 11. while( 1 ) 12. { 13. // :当按下 y 时退出 14. if ( _kbhit() && 'y'== _getch() ) 15. { 16. return; 17. } 18. } 19. } 版本二: 1. // crt_getch.c 2. // compile with: /c 3. // This program reads characters from 4. // the keyboard until it receives a 'Y' or 'y'. 5. #include 6. #include 7. int main( void ) 8. { 9. int ch; 10. _cputs( \"Type 'Y' when finished typing keys: \" ); 11. do 12. { 13. ch = _getch(); 14. ch = toupper( ch ); 15. } while( ch != 'Y' ); 16. _putch( ch ); 17. _putch( '/r' ); // Carriage return 18. _putch( '/n' ); // Line feed 19. } 因篇幅问题不能全部显示,请点此查看更多更全内容