KalEl
KalEl

Reputation: 9136

C#: Check if any key was pressed in Console

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 for the program to wait till a key is pressed?

Upvotes: 16

Views: 15442

Answers (3)

bytedev
bytedev

Reputation: 9099

Just add the following where you want to wait:

while (!Console.KeyAvailable) {}

Upvotes: 1

Smallgods
Smallgods

Reputation: 237

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.

Upvotes: 1

weismat
weismat

Reputation: 7411

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

Upvotes: 35

Related Questions