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

时间:2012-07-25 10:13:34

标签: c# console-application

我需要检查控制台应用程序中是否按下了任何键。键可以是键盘中的任何键。类似的东西:

if(keypressed)
{ 

//Cleanup the resources used

}

我想出了这个:

ConsoleKeyInfo cki;
cki=Console.ReadKey();

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

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

2 个答案:

答案 0 :(得分:15)

这可以帮到你:

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

答案 1 :(得分:5)

如果您想要非阻止,请查看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