Wait set time for user input C# console app

2020-06-23 08:04发布

问题:

For a Console app, I need to know how to wait at set amount of time (about 10 seconds), for a user to input a key or set of keys, before proceeding with an 'auto run' portion of the application.

This is bugging me because I can't quite figure out how the timer works, or threading.sleep, what should I use? Been googling all day.

some psuedocode:

1.app opens

2.app waits 10 secs for user to hit the "k" key.

3.if user hits k, go to 4. if user does not, go to 5.

4.run a function(open a form)

5.run a function(do something)

I bet its simple, I just don't understand whats going on.

回答1:

Set a 10 second timer off.

Fire an event when the timer expires.

In the event handler proceed with the "auto run" section.

If the user hits a key before the timer expires, kill the thread.

The Timer class page on MSDN has an example of a timer waiting for a set period.



回答2:

Here's some sample code for a C# console application. It doesn't use a timer, instead it uses Sleep. It may be a bit easier to understand than timer based code.

        static void openForm()
        {
            Console.WriteLine("Form opened!");
        }

        static void doSomething()
        {
            Console.WriteLine("Do something!");
        }

        static void Main(string[] args)
        {
            bool optionForm = false;
            int seconds = 1;

            Console.Write("Press 'k' to open form");

            while (true)
            {                
                if (Console.KeyAvailable)
                {
                    ConsoleKeyInfo c = Console.ReadKey(true);
                    if (c.Key == ConsoleKey.K)
                    {                        
                        optionForm = true;
                        break;
                    }
                }

                System.Threading.Thread.Sleep(1000);

                if (seconds++ > 10)
                    break;

                Console.Write('.');
            }

            Console.WriteLine();

            if (optionForm)
                openForm();
            else
                doSomething();

            Console.ReadKey();
        }


回答3:

Thanks Marlon!! It really helped me a lot..

I used following code:

int minutes = 1;
while (true)
{
   if (Console.KeyAvailable)
   {
        ConsoleKeyInfo c = Console.ReadKey(true);
    if (c.Key == ConsoleKey.Enter)
    {
            break;
    }
   }
   Thread.Sleep(1000);
   if (minutes++ > 10)
   {
    throw;
   }
}


回答4:

Here is some code that will do the trick for you too.

        Form1 f = new Form1();
        System.Threading.Timer t = new System.Threading.Timer(o => f.Invoke(new Action(() => f.textBox1.Enabled = true)), null, 10000, System.Threading.Timeout.Infinite);
        f.ShowDialog();
        t.Change(System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite);