Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Console ReadKey timeout [duplicate]

Tags:

c#

I have built a simple console application, and I need to give a specific time for user to input a keychar.

Should I use this?

System.Threading.Thread.Sleep(1000);

For those who didn't understand, I need the program to skip the Console.ReadKey().KeyChar; after x seconds.

Is this possible?

like image 890
user3107990 Avatar asked Dec 17 '13 07:12

user3107990


1 Answers

I would do it like this:

DateTime beginWait = DateTime.Now;
while (!Console.KeyAvailable && DateTime.Now.Subtract(beginWait).TotalSeconds < 5)
    Thread.Sleep(250);

if (!Console.KeyAvailable)
    Console.WriteLine("You didn't press anything!");
else
    Console.WriteLine("You pressed: {0}", Console.ReadKey().KeyChar);
like image 51
Tony Avatar answered Nov 12 '22 15:11

Tony