检测某个键是否按下-非阻塞模式处理键盘字符事件C语言
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
检测某个键是否按下,-非阻塞模式,处理键盘字符事件C语言
通常我们的很多程序都是一个whi le循环,想在按下某个按键时退出.如何检测这个键按下?
通常有两种方式来做
一利用阻塞函数来做.
利用阻塞函数检测按键,又不想让主线程阻塞, 就可以另开一个线程,在线程里面检测按键是否按下. 好像老吉在l inux下的版本
就是这样实现的. 通过一个全局变量和主线程通信.
二利用非阻塞函数来做.
版本一:
1./* KBHIT.C: This progra m loops until the user
2.* presse s a key. If _kbhit return s nonzer o, a
3.* keystr oke is waitin g in the buffer. The pro
gra m
4.* can call _getch or _getch e to get the key
str oke.
5.*/
6.//
7.#includ e <conio.h>
8.#includ e <stdio.h>
9.
10.void main( void )
11.{
12. while( 1 )
13. {
14. // :当按下 y 时退出
15. if ( _kbhit() && 'y'== _getch() )
16. {
17. return;
18. }
19. }
20.}
版本二:
1.// crt_ge tch.c
2.// compil e with: /c
3.// This progra m readscharac tersfrom
4.// the keyboa rd untilit receiv es a 'Y' or 'y'.
5.
6.
7.#includ e <conio.h>
8.#includ e <ctype.h>
9.
10.int main( void )
11.{
12. int ch;
13.
14. _cputs( "Type 'Y' when finish ed typing keys: " );
15. do
16. {
17. ch = _getch();
18. ch = touppe r( ch );
19. } while( ch != 'Y' );
20.
21. _putch( ch );
22. _putch( '/r' ); // Carria ge return
23. _putch( '/n' ); // Line feed
24.}
25.。