Possible Duplicate:
How to add a Timeout to Console.ReadLine()?
If I have a Console.ReadKey(), It makes the whole program stuck, how can I make it so that it will read a key for 1 second, and if a key is not read, something else would be set.
Possible Duplicate:
How to add a Timeout to Console.ReadLine()?
If I have a Console.ReadKey(), It makes the whole program stuck, how can I make it so that it will read a key for 1 second, and if a key is not read, something else would be set.
The console has a property
KeyAvailable
. But your desired functionality (timeout) is not available. You could write your own functionThis function loops until the desired time in milliseconds has elapsed or a key has been pressed. It checks to see whether a key is available before it calls
Console.ReadKey();
. The checkConsole.KeyAvailable
continues immediately, whether a key is available or not. It returnstrue
if a key has been pressed and is ready to be read byReadKey
andfalse
otherwise. If no key is available the function sleeps for 50 ms until it performs the next loop. This is better than looping without sleeping, because that would give you 100% CPU usage (on one core).The function returns a
ConsoleKeyInfo
asReadKey
would, in case you want to know which key the user has pressed. The last line creates an emptyConsoleKeyInfo
(see ConsoleKeyInfo Structure and ConsoleKeyInfo Constructor). It allows you to test whether the user pressed a key or whether the function timed out.Do you mean something like this?