发新话题
打印

如何通过判断按键来退出循环

如何通过判断按键来退出循环

  前几天在c#版中看到一个帖子:“如何用c#实现,在while (true)循环中,按Esc键退出循环?" 那时候以为只能用hook来监视键盘,看了看后面一些猩猩的回复,只怪自己c#太菜,都没有看明白:( 昨天在c版看到又有人问这个问题,其中cyberHunK(→迈克·老猫←) 用了_kbhit()来解决了这个问题,我又去查了查MSDN,才有点明白,终于知道了还有_kbhit()这样的函数(汗。。。)。觉得这个东西蛮有用的,就记下来,有错的地方还请各位指教!
先抄一段MSDN对_kbhit()的解释:
int _kbhit( void );
Return Value
_kbhit returns a nonzero value if a key has been pressed. Otherwise, it returns 0.

Remarks
The _kbhit function checks the console for a recent keystroke. If the function returns a nonzero value, a keystroke is waiting in the buffer. The program can then call _getch or _getche to get the keystroke.
所以在vc里面可以用下面这个程序来实现按ESC退出while循环
#include
#include //包含对 _kbhit()和_getch()声明

int main()
{
bool flag = true;
char unch;
while(flag)
if(_kbhit()

TOP

  下面这个程序中就用到了这种方法,用于判断在3秒中内是否有键按下。(vs2005下编译运行通过)
using System;
using System.Runtime.InteropServices;
using System.Threading;

namespace ConsoleApplication2
{
class Program
{
[DllImport("msvcrt.dll")]
public static extern int _getch();
[DllImport("msvcrt.dll")]
public static extern int _kbhit();

static void Main(string[] args)
{
Console.WriteLine("Press Any Key to Continue");
int counter = 0;

while ((_kbhit() == 0)

TOP

发新话题