Ways of console pausing
Asked Answered
C

6

6

As I'm new to C#, I searched Google for various stuff which I used to use in C++. One of them is a pause possibility in a console app.

A lot of people suggested different ways like

System.Console.ReadKey(true);
System.Console.WriteLine();

Others even showed self-made functions which 'should' be more efficient than others. And that's a real headache to decide which one is a better solution.

Could anyone give any examples of how C# interpret them and which way should be the most efficient?

Carleencarlen answered 1/12, 2012 at 17:36 Comment(5)
If I may ask - why should pausing be efficient!?Institute
I know that it doesn't make huge different in small apps, but thinking theoretical, which is better.Carleencarlen
Why would you pause it is the first question you should ask yourself.Portend
Homework assignment, need to print out something in the end of calculations, can't do that without pausing it, right?Carleencarlen
@RnD: the exercise is pointless. There will never be some theoretical situation where efficient pausing is necessary, and even if there were some corner case where it was, you'd be better off spending your time thinking about real problems. This is a case of micro-optimization and premature optimization, both of which are bad.Palmer
R
8

Run the program using any of the following methods:

  1. ctrl + F5

OR as Rajesh suggested

  1. Console.ReadKey() //pauses for any key
  2. Console.ReadLine() //pauses for enter key
Repay answered 10/8, 2016 at 16:49 Comment(1)
ctrl + F5 did the job!Flopeared
H
3

I usually use do and while to pause the console. Then, if necessary, the console should resume if you press a specific key.

Example

do
{

/*  while (!Console.KeyAvailable) //Continue if pressing a Key press is not available in the input stream
    {
        //Do Something While Paused
    } 
*/

} while (Console.ReadKey(true).Key != ConsoleKey.Escape); //Resume if Escape was pressed

If you leave this as //Do Something While Paused, the console will only resume if the Esc key was pressed doing nothing while paused.

However, if you would not like the console application to resume, you can use while (true); instead of while (Console.ReadKey(true).Key != ConsoleKey.Escape);

Example

do
{
    //break; //Resume
} while (true); //Continue while True (Always True)

Notice: The console application will pause because by doing do { } while (Condition); you are simply telling the console application that you are doing something. So, the console application will wait for the operation to execute. Then, normally close when there's nothing to do.
Notice: The while is used to loop. So, the application will not close unless the condition becomes false.

Thanks,
I hope you find this helpful :)

Hysterogenic answered 1/12, 2012 at 17:49 Comment(0)
C
1

If you're talking about the built-in "pause" command, you could always call it -- even though it's ugly. Here's what I use:

static void Pause()
{
    Console.WriteLine();
    var pauseProc = Process.Start(
        new ProcessStartInfo()
            {
                FileName = "cmd",
                Arguments = "/C pause",
                UseShellExecute = false
            });
    pauseProc.WaitForExit();
}

Normally like so:

if (Environment.UserInteractive())
    Pause();

Hope this helps.

Checkoff answered 7/6, 2013 at 10:6 Comment(2)
The built-in pause command just waits for a keypress. Why would you launch an external process to wait for a keypress, when you're in a programming language that can just wait for a keypress?Overissue
Good point, and this was asked & answered 11 years ago. Guess I either mis-read the question at the time, or took it as a programming challenge to call pause? Either way, be careful with that "just", I'm sure there's plenty of good logic behind there. Good necromancing though, take your badge! :)Checkoff
H
1

Or you can use what Pat did but for Arguments instead of

Arguments = "/C pause"

you can use

Arguments = "/C TIMEOUT /t 4 /nobreak > NUL"

where number 4 is number of seconds console will pause before executing rest of the program.

And the whole function would be

static void Pause(int sec)
    {
        Console.WriteLine();
        var pauseProc = Process.Start(
            new ProcessStartInfo()
            {
                FileName = "cmd",
                Arguments = "/C TIMEOUT /t " + sec + " /nobreak > NUL",
                UseShellExecute = false
            });
        pauseProc.WaitForExit();
    }

and you will call it with Pause function with number of seconds to pause.

Pause(4);

Hope it helps.

Hallett answered 23/7, 2014 at 8:22 Comment(0)
L
0

Putting this out there if anyone wants the same look and feel of Press any key to continue . . .

This one is simple and without any DLL import:

private static void Pause() {
    Console.Write("Press any key to continue . . . ");
    // ReadKey(Boolean) = true to not display the pressed key
    // https://learn.microsoft.com/en-us/dotnet/api/system.console.readkey
    Console.ReadKey(true);
}

Or, if you really want the old school flavor (Windows only):

using System.Runtime.InteropServices;

class Whatever {

    [DllImport("msvcrt.dll")]
    // "system" has to be lowercase
    static extern bool system(string str);

    static void Main(string[] args) {
        system("pause");
    }

}

NOTE: Both ReadKey() and DllImport("msvcrt.dll") do not respond to pressing a modifier key (Alt, Ctrl, or Shift) by itself. So you're better of just using ReadKey().

Lour answered 7/5 at 19:26 Comment(0)
B
-2

you can write "Console.ReadLine();" this too for pupose.

Burma answered 13/8, 2015 at 18:51 Comment(1)
This is already covered in the answer by Rajesh. If you found an answer helpful, you should upvote that answer when you have earned that privilege.Phenacaine

© 2022 - 2024 — McMap. All rights reserved.