How to stop C# console applications from closing automatically? [duplicate]

回眸只為那壹抹淺笑 提交于 2019-11-26 06:46:41
Console.ReadLine();

or

Console.ReadKey();

ReadLine() waits for , ReadKey() waits for any key (except for modifier keys).

Edit: stole the key symbol from Darin.

Silvia Z

You can just compile (start debugging) your work with Ctrl+F5.

Try it. I always do it and the console shows me my results open on it. No additional code is needed.

Try Ctrl + F5 in Visual Studio to run your program, this will add a pause with "Press any key to continue..." automatically without any Console.Readline() or ReadKey() functions.

Console.ReadLine() to wait for the user to Enter or Console.ReadKey to wait for any key.

Use:

Console.ReadKey();

For it to close when someone presses any key, or:

Console.ReadLine();

For when the user types something and presses enter.

Ctrl + F5 is better, because you don't need additional lines. And you can, in the end, hit enter and exit running mode.

But, when you start a program with F5 and put a break-point, you can debug your application and that gives you other advantages.

Alternatively, you can delay the closing using the following code:

System.Threading.Thread.Sleep(1000);

Note the Sleep is using milliseconds.

Those solutions mentioned change how your program work.

You can off course put #if DEBUG and #endif around the Console calls, but if you really want to prevent the window from closing only on your dev machine under Visual Studio or if VS isn't running only if you explicitly configure it, and you don't want the annoying 'Press any key to exit...' when running from the command line, the way to go is to use the System.Diagnostics.Debugger API's.

If you only want that to work in DEBUG, simply wrap this code in a [Conditional("DEBUG")] void BreakConditional() method.

// Test some configuration option or another
bool launch;
var env = Environment.GetEnvironmentVariable("LAUNCH_DEBUGGER_IF_NOT_ATTACHED");
if (!bool.TryParse(env, out launch))
    launch = false;

// Break either if a debugger is already attached, or if configured to launch
if (launch || Debugger.IsAttached) {
    if (Debugger.IsAttached || Debugger.Launch())
        Debugger.Break();
}

This also works to debug programs that need elevated privileges, or that need to be able to elevate themselves.

If you do not want the program to close even if a user presses anykey;

 while (true) {
      System.Console.ReadKey();                
 };//This wont stop app
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!