How to Keep Console Window Open

How to keep console window open

You forgot calling your method:

static void Main(string[] args)
{
StringAddString s = new StringAddString();
s.AddString();
}

it should stop your console, but the result might not be what you expected, you should change your code a little bit:

Console.WriteLine(string.Join(",", strings2));

How to keep Console Window open after execution?

You can use the pause-command inside C# if you want:
I use it as follows:

Solution №1:

//optional: Console.WriteLine("Press any key ...");
Console.ReadLine(true);

Solution №2: (Uses P/Invoke)

// somewhere in your class
[DllImport("msvcrt.dll", CallingConvention = CallingConvention.Cdecl, SetLastError=true)]
public static extern int system(string command);

public static int Main(string[] argv)
{
// your code

system("pause"); // will automaticly print the localized string and wait for any user key to be pressed
return 0;
}



EDIT: you can create a temporary batch file dynamically and execute it, for example:

string bat_path = "%temp%/temporary_file.bat";
string command = "command to be executed incl. arguments";

using (FileStream fs = new FileStream(bat_path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read))
using (StreamWriter sw = new StreamWriter(fs, Encoding.Default))
{
sw.WriteLine("@echo off");
sw.WriteLine(command);
sw.WriteLine("PAUSE");
}

ProcessStartInfo psi = new ProcessStartInfo() {
WorkingDirectory = Path.GetDirectoryName(YourApplicationPath),
RedirectStandardOutput = true,
RedirectStandardInput = true,
RedirectStandardError = true,
CreateNoWindow = false,
UseShellExecute = false,
WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal
};

Process p = new Process() {
StartInfo = psi;
};
p.Start();

int ExitCode;
p.WaitForExit();

// *** Read the streams ***
string output = p.StandardOutput.ReadToEnd();
string error = p.StandardError.ReadToEnd();

ExitCode = p.ExitCode;

MessageBox.Show("output>>" + (String.IsNullOrEmpty(output) ? "(none)" : output));
MessageBox.Show("error>>" + (String.IsNullOrEmpty(error) ? "(none)" : error));
MessageBox.Show("ExitCode: " + ExitCode.ToString(), "ExecuteCommand");
p.Close();

File.Delete(bat_path);

JavaScript Keep Console Window Open in Visual Studio

So it turns out that ctrl + f5 will open a console that stays open. Interestingly, there are two similar questions on stackoverflow about this, here and here, but the "solution" does not work in my Windows 10 / VS 2017 environment. I'll stick with using ctrl + f5, or running node filename.js in a terminal window.

Keep console window open

Given the discussions so far in comments, my first recommendation is definitely to create a System Tray application for this. This would allow for user interaction and notifications without having to keep a Console window on the desktop.

Failing that, you could perhaps implement something like a "game loop" in your console. How "real time" do the statistics need to be? One-second delayed maybe? Something like this:

while (true)
{
Thread.Sleep(1000);
DisplayCurrentStats();
}

This would pause the main thread (not always recommended, but it is the UI that you're trying to keep open here) and then output the display every second. (If the output is already handled by something else and for whatever reasons shouldn't be moved here, just ignore that part.)

You'd probably still want some way of breaking out of the whole thing. Maybe an escape input:

while (true)
{
Thread.Sleep(1000);
DisplayCurrentStats();
var escape = Console.Read();
if (IsEscapeCharacter(escape))
break;
}
OutputGoodByeMessage();

In the IsEscapeCharacter() method you can check if the character read from the Console (if there was one) matches the expected "escape" character. (The esc key seems like a standard choice, though for obscurity you can use anything else in order to try to prevent "accidental escape.") This would allow you to terminate the application cleanly if you need to.

It's still at 1-second delay increments, which isn't ideal. Though even at 1/10-second it's still spending the vast majority of its time sleeping (that is, not consuming computing resources) while providing some decent UI responsiveness (who complains about a 1/10-second delay?):

Thread.Sleep(100);

How to keep the console window open in Visual C++?

Start the project with Ctrl+F5 instead of just F5.

The console window will now stay open with the Press any key to continue . . . message after the program exits.

Note that this requires the Console (/SUBSYSTEM:CONSOLE) linker option, which you can enable as follows:

  1. Open up your project, and go to the Solution Explorer. If you're following along with me in K&R, your "Solution" will be 'hello' with 1 project under it, also 'hello' in bold.
  2. Right click on the 'hello" (or whatever your project name is.)
  3. Choose "Properties" from the context menu.
  4. Choose Configuration Properties>Linker>System.
  5. For the "Subsystem" property in the right-hand pane, click the drop-down box in the right hand column.
  6. Choose "Console (/SUBSYSTEM:CONSOLE)"
  7. Click Apply, wait for it to finish doing whatever it does, then click OK. (If "Apply" is grayed out, choose some other subsystem option, click Apply, then go back and apply the console option. My experience is that OK by itself won't work.)

CTRL-F5 and the subsystem hints work together; they are not separate options.

(Courtesy of DJMorreTX from http://social.msdn.microsoft.com/Forums/en-US/vcprerelease/thread/21073093-516c-49d2-81c7-d960f6dc2ac6)

Keep console window of a new Process open after it finishes

This will open the shell, start your executable and keep the shell window open when the process ends

Process p = new Process();
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "CMD.EXE";
psi.Arguments = "/K yourmainprocess.exe";
p.StartInfo = psi;
p.Start();
p.WaitForExit();

or simply

ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "CMD.EXE";
psi.Arguments = "/K yourmainprocess.exe";
Process p = Process.Start(psi);
if(p != null && !p.HasExited)
p.WaitForExit();

How to keep console window open even after program started from batch-file has been terminated?

start /wait tells batch to wait for the program to terminate, before performing next line, or to finish script. to keep it open and do nothing you can use pause:

@ECHO OFF
title test
@ECHO ON
"C:\My CLI Tools\7zip\x64\7za.exe"
pause

Or timeout:

@ECHO OFF
title test
@ECHO ON
start "" /WAIT "C:\My CLI Tools\7zip\x64\7za.exe"
timeout /t 300

But both these will do nothing until it either times out, or you press any key.

If you were expecting output in cmd window, and the command actually provides output to cmd console, then you should not start it outside of the current console window. Just do:

@ECHO OFF
title test
@ECHO ON
"C:\My CLI Tools\7zip\x64\7za.exe"
pause

Keeping Console Window Open in Visual Studio (C)

See also How to keep the console window open in Visual C++?

How do I keep a console window open after my python program terminates to see any errors produced?

Solution 1:

I just saw your comment:

When I do that, I recieve the error 'python' is not recognized as an
internal or external command, operable program or batch file

It looks like you haven't specified the path to the python executable: you need to add the python executable path to your Window's PATH variable. You can see how to do that here: Add Python to the PATH Environmental Variable (‘python’ is not recognized as an internal or external command)

Solution 2:

You can use input("enter to exit") at the end of your python code to keep the program alive. It would exit once you press enter.

You could also surround your code in a try except statement and place thr input() in the except to prevent the program from exiting when there are errors, but like @Kevin mentioned in the comments, this would catch run time errors but not syntax errors.

Solution 3:

You can write errors or anything information you want to a file such as log.txt for example, and then read that log file once the code finishes running e.g. how to write to a file in Python



Related Topics



Leave a reply



Submit