1.源自 头文件<conio.h>
2. 原型:extern int kbhit(void);
用法:#include <stdio.h>
功能:检测按键
说明:检测键盘是否有键按下。
如果有键按下,则返回对应键值;否则返回零。
kbhit不等待键盘按键。无论有无按键都会立即返回。
举例:
// kbhit.c
#include <stdio.h>
main()
{
int i=0;
clrscr();
while(!kbhit())
{
clrscr();
printf("%05d",i++);
}
clrscr();
printf("End.");
getchar();
return 0;
}
3.kbhit()检测键盘是否有键按下,并工作在非阻塞模式下(即不等待状态,如果没有键按下,函数立即返回),如果有键按下,函数返回按键的ACSII码,
例子(来源MSDN):
/* 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 <conio.h>#include <stdio.h>void main( void ){ /* Display message until key is pressed. */ while( !_kbhit() ) _cputs( "Hit me!! " ); /* Use _getch to throw key away. */ printf( "\nKey struck was '%c'\n", _getch() ); _getch();}
Output
Hit me!! Hit me!! Hit me!! Hit me!! Hit me!! Hit me!! Hit me!!Key struck was 'q'
利用此函数可实现在程序运行时按任意键继续的以功能,非常好用
如果程序是循环式的,可在循环程序中加入
while(!kbhit())
{
char c;
cout<<"按任意键继续程序执行,按q按退出程序";
cin>>c;
if(c=='q')
return 1;
}
如果程序不是循环时的,而是非常长的一个程序串,就要通过多线程来实现,另外创建一个线程,在新线程中使用kbhit()函数,然后调用API函数SuspendThread 暂停主线程的运行就可以了
- [nanjixing8119] 我也问和这个朋友同样的问题[ andyhl333 发表于 2011-05-26 18:55 11/24 20:56
- [andyhl333] 前言上说要学习本书就要具备以下基础: 1,具有计算机使用经验; 2,具有二进制、十六进制等基础知 05/26 18:55
- [masmaster] 学习~~~ 07/10 14:28
- [761114] 说的太好了,你叫我怎么夸你呢!这样吧,给你一句话吧。你太有才了!!!!!!! 06/09 22:51
- [hao76762401] 顶那三条原则! 05/23 19:32
- [1119174611] 一、没有通过检测点不要向下学习, 二、没有做完当前实验不要向下学习。 我觉得 二、没有做完当 05/10 00:37
- [hejianliangjia] 看到这篇文章大家很幸运,我是吃了不少苦头才悟到,不过 “一、没有通过检测点不要向下学习, 二、 05/04 01:01
- [游客] 哈哈,向自己学,汇编的书好难懂的,看不下去了 05/01 20:32
- [lenient315] 说的不错 看完王爽老师的书后看看LZ推荐的 04/21 11:27
- [qingjiaozhe2010] 太深奥了,现在还不理解 04/08 11:33