检查控制台应用程序 C# 中是否按下了任何键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11647486/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 18:39:31  来源:igfitidea点击:

Checking if any key pressed in console application C#

c#console-application

提问by user1502952

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

}

I had come up with this:

我想出了这个:

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?

它适用于除修饰键之外的所有键 - 我如何检查这些键?

采纳答案by Ionic? Biz?u

This can help you:

这可以帮助您:

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:

如果你想在一个中使用它if,你可以试试这个:

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

For any key is very simple: remove the if.

对于任何键非常简单:删除if.



As @DawidFerenczymentioned we have to note that Console.ReadKey()is blocking. It stops the execution and waits until a key is pressed. Depending on the context, this may (not) be handy.

正如@DawidFerenczy提到的,我们必须注意这Console.ReadKey()是阻塞的。它停止执行并等待直到按下某个键。根据上下文,这可能(不)方便。

If you need to not block the execution, just test Console.KeyAvailable. It will contain trueif a key was pressed, otherwise false.

如果您不需要阻止执行,只需 test Console.KeyAvailable。它将包含true是否按下了一个键,否则false.

回答by John Mitchell

Have a look at the Console.KeyAvailibleif you want nonblocking.

Console.KeyAvailible如果您想要非阻塞,请查看。

do {
    Console.WriteLine("\nPress a key to display; press the 'x' key to quit.");

// Your code could perform some useful task in the following loop. However, 
// for the sake of this example we'll merely pause for a quarter second.

    while (Console.KeyAvailable == false)
        Thread.Sleep(250); // Loop until input is entered.
    cki = Console.ReadKey(true);
    Console.WriteLine("You pressed the '{0}' key.", cki.Key);
    } while(cki.Key != ConsoleKey.X);
}

If you want blocking then use Console.ReadKey.

如果你想阻塞然后使用Console.ReadKey.