我需要检查控制台应用程序中是否有按键被按下。按键可以是键盘上的任何键。例如:
if(keypressed)
{
//Cleanup the resources used
}
我想出了这个:
ConsoleKeyInfo cki;
cki=Console.ReadKey();
if(cki.Equals(cki))
Console.WriteLine("key pressed");
它能够很好地处理除修饰键以外的所有按键 - 我该如何检查这些按键?
我需要检查控制台应用程序中是否有按键被按下。按键可以是键盘上的任何键。例如:
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
语句。
Console.ReadKey()
是阻塞的。它会停止执行并等待按下一个键。根据上下文,这可能(不)方便。Console.KeyAvailable
。如果有键被按下,它将包含 true
,否则为false
。如果您想要非阻塞,请查看Console.KeyAvailable
。
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
。