Search code examples
c#console-applicationkeystorereadlineconsole.readline

capture keystroke without blocking


I usually use Console.ReadLine(); to capture a single keystroke. But this function blocks execution and keeps waiting for it to happen.

Is it possible, inside a loop, to capture it if it's pressed and continue execution if it's not?

The best would be something similar to GUI apps, that keep running and anytime a shortcut is executed it's intercepted and an event throws to be captured. But I doubt console apps are able to do that.

The second best solution would be a Console.ReadLine(); that waits for 1 second and then returns. If user is holding a keyboard button while the function is called, the function identifies the keystroke and returns with its char, otherwise the function returns with null.


Solution

  • Have you read MSDN Key press info for console?

    You can use Console.KeyAvailable to determine if you actually want to get the key in the queue.