检测某个键是否按下,-非阻塞模式,处理键盘字符事件C语言
通常我们的很多程序都是一个while循环, 想在按下某个按键时退出.如何检测这个键按下?
通常有两种方式来做
一 利用阻塞函数来做.
利用阻塞函数检测按键, 又不想让主线程阻塞, 就可以另开一个线程,在线程里面检测按键是否按下. 好像老吉在linux下的版本
就是这样实现的. 通过一个全局变量和主线程通信.
二 利用非阻塞函数来做.
版本一:
1.
2.
3.
4.
5.
6.
7.
8.
9. /* KBHIT.C: This program loops until the user * presses a key. If _kbhit returns nonzero, a * keystroke is waiting in the buffer. The program * can call _getch or _getche to get the keystroke. */ // #include #include
10. void main( void )
11. {
12. while( 1 )
13. {
14. // :当按下 y 时退出
15. if ( _kbhit() && 'y'== _getch() )
16. {
17. return;