C#: Check if any key was pressed in Console

前端 未结 3 1091
野性不改
野性不改 2020-12-16 14:29

Both Console.Read() and Console.ReadKey() seem to wait for a key to be pressed. How can I detect if anything was pressed without actually asking fo

相关标签:
3条回答
  • 2020-12-16 15:11

    Just add the following where you want to wait:

    while (!Console.KeyAvailable) {}
    
    0 讨论(0)
  • 2020-12-16 15:25

    You can poll on Console.KeyAvailable to know if you can read anything.

    0 讨论(0)
  • 2020-12-16 15:31

    You want to look into using Event Handlers. For using Windows forms the following should be helpful. Control.Keypress Event (System.Windows.Forms). For a good overview of Event Handlers in general, take a look at EventHandling in .NET using C#.

    For a console application, you should look into the Console.CancelKeyPress Event function.

    0 讨论(0)
提交回复
热议问题