检查是否任何按键在控制台应用程序C#压制

检查是否任何按键在控制台应用程序C#压制

问题描述:

我需要检查是否有任何键是在一个控制台应用程序按下。键可以在键盘上的任意键。是这样的:

I need to check if any key is pressed in a console application. The key can be any key in the keyboard. Something like:

if(keypressed)
{ 

//Cleanup the resources used

}

我想出了这一点:

ConsoleKeyInfo cki;
cki=Console.ReadKey();

if(cki.Equals(cki))
Console.WriteLine("key pressed");



据除外修饰键所有按键效果很好 - 我怎么能检查这些键

It works well with all keys except modifier keys - how can I check these keys?

这可以帮助你:

Console.WriteLine("Press any key to stop");
do {
    while (! Console.KeyAvailable) {
        // Do something
   }       
} while (Console.ReadKey(true).Key != ConsoleKey.Escape);

修改

如果你想使用它的如果,你可以试试这个:

If you want to use it in an if, you can try this:

ConsoleKeyInfo cki;
while (true)
{
   cki = Console.ReadKey();
   if (cki.Key == ConsoleKey.Escape)
     break;
}

有关任何按键非常简单:删除如果

For any key is very simple: remove the if.