简体   繁体   English

C#:检查控制台中是否按下了任何键

[英]C#: Check if any key was pressed in Console

Both Console.Read() and Console.ReadKey() seem to wait for a key to be pressed. Console.Read()Console.ReadKey()似乎都在等待按下某个键。 How can I detect if anything was pressed without actually asking for the program to wait till a key is pressed? 如果没有实际要求程序等到按下某个键,我如何检测是否有任何按下?

您可以在Console.KeyAvailable上进行轮询,以了解您是否可以阅读任何内容。

You want to look into using Event Handlers. 您想要研究使用事件处理程序。 For using Windows forms the following should be helpful. 对于使用Windows表单,以下内容应该会有所帮助。 Control.Keypress Event (System.Windows.Forms) . Control.Keypress事件(System.Windows.Forms) For a good overview of Event Handlers in general, take a look at EventHandling in .NET using C# . 有关一般事件处理程序的概述,请使用C#查看.NET中的EventHandling

For a console application, you should look into the Console.CancelKeyPress Event function. 对于控制台应用程序,您应该查看Console.CancelKeyPress Event函数。

只需添加以下您要等待的位置:

while (!Console.KeyAvailable) {}

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

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