汇编网首页登录博客注册
acool的学习博客
博客首页博客互动【做检测题】论坛求助

我的博客

个人首页 |  我的文章 |  我的相册 |  我的好友 |  最新访客 |  文章收藏 |  论坛提问 |  友情链接 |  给我留言  
图片载入中
  •  --
  • 『姓名』:来,留,去
  • 『性别』:男『发送消息
  • 个人说明:.
    .  
      世间是一个大苦海。 
      人在海中。 
      肉身是船。 
      魂儿是船里的人。 
      船载着人,一直向彼岸行驶。
      ...
    .
  • 详细信息『加为好友』
学习动态
最新留言
友情链接

[2009-07-20 17:05] int kbhit(void)函数

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 暂停主线程的运行就可以了
评论次数(0)  |  浏览次数(1199)  |  类型(C/C++) |  收藏此文  | 
 
 请输入验证码  (提示:点击验证码输入框,以获取验证码