繁体   English   中英

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

[英]Checking if any key pressed in console application C#

我需要检查控制台应用程序中是否按下任何键。 键可以是键盘中的任何键。 就像是:

if(keypressed)
{ 

//Cleanup the resources used

}

我想出了这个:

ConsoleKeyInfo cki;
cki=Console.ReadKey();

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

它适用于除修改键以外的所有键 - 如何检查这些键?

这可以帮助您:

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

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

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

对于任何键都很简单:删除if


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

如果您不需要阻止执行,只需测试Console.KeyAvailable 如果按下某个键,它将包含true ,否则为false

如果您想要非阻塞,请查看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);
}

如果您想要阻止,请使用Console.ReadKey

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM