受欢迎的博客标签

如何用c#实现,在while (true)循环中,按Esc键用int _kbhit( void ) 函数退出循环?

Published

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 functionreturns a nonzero value, a keystroke is waiting in the buffer. The program can then call _getch or _getche to get the keystroke.

下面这个程序中就用到了这种方法,用于判断在3秒中内是否有键按下。

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) counter < 30)

{

Thread.Sleep(100);

counter++;

}

if (counter < 30)

{

Console.WriteLine("you pressed " + (char)_getch());

}

else

{

Console.WriteLine("You did not press anything using default after 3seconds");

}

}

}

}

程序不停的输出“循环中”,按a退出

using System;

namespace ConsoleApplication2

{

class Program

{

static void Main(string args)

{

bool a = false;

ConsoleKeyInfo keyInfo;

while (!a)

{

if (System.Console.KeyAvailable)//如果有键按下

{

keyInfo = System.Console.ReadKey(true);//读取

if (keyInfo.KeyChar 0x1b)//判断

a = true;

}

else

System.Console.WriteLine("循环中");

}

}

}

}