C# 检查控制台应用程序C中是否按下了任何键#
我需要检查控制台应用程序中是否按下了任何键。该键可以是键盘上的任意键。比如:C# 检查控制台应用程序C中是否按下了任何键#,c#,console-application,C#,Console Application,我需要检查控制台应用程序中是否按下了任何键。该键可以是键盘上的任意键。比如: if(keypressed) { //Cleanup the resources used } 我想到了这个: ConsoleKeyInfo cki; cki=Console.ReadKey(); if(cki.Equals(cki)) Console.WriteLine("key pressed"); 它适用于除修改器关键点之外的所有关键点-如何检查这些关键点?如果需要非阻塞,请查看 do { C
if(keypressed)
{
//Cleanup the resources used
}
我想到了这个:
ConsoleKeyInfo cki;
cki=Console.ReadKey();
if(cki.Equals(cki))
Console.WriteLine("key pressed");
它适用于除修改器关键点之外的所有关键点-如何检查这些关键点?如果需要非阻塞,请查看
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);
}
如果要阻止,请使用控制台。ReadKey这可以帮助您:
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;
}
对于任何键都非常简单:如果,请删除
如前所述,我们必须注意,Console.ReadKey()
正在阻塞。它停止执行并等待,直到按下一个键。根据上下文,这可能(不是)很方便
如果不需要阻止执行,只需测试Console.KeyAvailable
。如果按下一个键,它将包含true
,否则false
是否可以使用like if(cki.key==ConsoleKey.Enter)。不要指定ConsoleKey.Enter,而是在循环consoleKeyInfo cki时需要避免一次检查所有键;cki=Console.ReadKey();如果(cki.Equals(cki))控制台写入线(“按键”);除了修改键外,所有键都能很好地工作。哇,自从我回答问题以来,您的问题已经改变了很多。应该提到的是,Console.ReadKey()
正在阻塞,它停止执行并等待一个键被按下。这可能是一个问题,具体取决于需求。如果不需要阻止执行,只需测试Console.KeyAvailable
。如果按下某个键,它将包含true
,否则false
@dawiderency谢谢!编辑我的答案。:)