65

I figure out how to launch a process. But my problem now is the console window (in this case 7z) pops up frontmost blocking my vision and removing my focus interrupting my sentence or w/e i am doing every few seconds. Its extremely annoying, how do i prevent that from happening. I thought CreateNoWindow solves that but it didnt.

NOTE: sometimes the console needs user input (replace file or not). So hiding it completely may be a problems a well.

This is my current code.

void doSomething(...)
{
    myProcess.StartInfo.FileName = ...;
    myProcess.StartInfo.Arguments = ...;
    myProcess.StartInfo.CreateNoWindow = true;
    myProcess.Start();
    myProcess.WaitForExit();
}
John Saunders
  • 160,644
  • 26
  • 247
  • 397

4 Answers4

98

If I recall correctly, this worked for me

Process process = new Process();

// Stop the process from opening a new window
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;

// Setup executable and parameters
process.StartInfo.FileName = @"c:\test.exe"
process.StartInfo.Arguments = "--test";

// Go
process.Start();

I've been using this from within a C# console application to launch another process, and it stops the application from launching it in a separate window, instead keeping everything in the same window.

Mun
  • 14,098
  • 11
  • 59
  • 83
  • When I set `RedirectStandardOutput ` to `true` I didn't get any output in the default console, commenting that line out gave me output in the default console (I'm creating a console app). – MDMoore313 Nov 29 '16 at 17:23
  • 3
    This seems to cause an issue with `process.WaitForExit`. I ended up using `process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden` instead which appears to work fine. – oscilatingcretin Jun 01 '18 at 23:17
  • @oscilatingcretin WaitForExit may lead to deadlock due to limited buffer size of standard output. The right way to solve it to read the StandardOutput before calling of WaitForExit method. https://stackoverflow.com/a/139604/852284 – nicolas2008 Oct 06 '21 at 21:46
28

@galets In your suggestion, the window is still created, only it begins minimized. This would work better for actually doing what acidzombie24 wanted:

myProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
codefox
  • 289
  • 3
  • 2
4

Try this:

myProcess.StartInfo.WindowStyle = ProcessWindowStyle.Minimized;
galets
  • 17,802
  • 19
  • 72
  • 101
3

I'll have to double check, but I believe you also need to set UseShellExecute = false. This also lets you capture the standard output/error streams.

Paul Alexander
  • 31,970
  • 14
  • 96
  • 151