Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I "Pause" a console application when the user presses escape?

I am creating a C# console application that will be performing an infinite process. How can I get the application to "pause" when the user presses the escape key?

Once the user presses the escape key I want the option to either exit the application or continue the loop right where it left off. I don't want any discontinuity in the process. If I press Esc at step 100 I should be able to pick right back up at step 101.

Here is my method so far:

    // Runs the infinite loop application 
    public static void runLoop()
    {
        int count = 0;
        while (Console.ReadKey().Key!= ConsoleKey.Escape)
        {
                WriteToConsole("Doing stuff.... Loop#" + count.ToString());
                for (int step = 0; step <= int.MaxValue; step++ ) {
                    WriteToConsole("Performing step #" + step.ToString());
                    if (step == int.MaxValue)
                    {
                        step = 0; // Re-set the loop counter
                    }
                }


                count++;
        }

        WriteToConsole("Do you want to exit?  y/n");
        exitApplication(ReadFromConsole());
    }

Is there any way to check for the user input key in a separate thread then pause the infinite loop when the other thread sees an Esc key-press?

like image 528
Hooplator15 Avatar asked Oct 15 '15 18:10

Hooplator15


1 Answers

To find out if there is a key available in the loop, you can do this:

while (someLoopCondition)
{
    //Do lots of work here
    if (Console.KeyAvailable)
    {
        var consoleKey = Console.ReadKey(true);  //true keeps the key from
                                                 //being displayed in the console
        if (consoleKey.Key == ConsoleKey.Escape)
        {
            //Pause here, ask a question, whatever.
        }
    }
}

Console.KeyAvailable returns true if there is a key in the input stream ready to read and it is a non-blocking call so it won't pause to wait for input. You can check if the escape key was pressed and pause or do whatever you want if the condition is true.

like image 57
Ron Beyer Avatar answered Sep 24 '22 05:09

Ron Beyer