Hide console window from Process.Start C#

Prasad picture Prasad · Mar 21, 2011 · Viewed 132.1k times · Source

I am trying to create process on a remote machine using using System.Diagnostics.Process class. I am able to create a process. But the problem is, creating a service is take a long time and console window is displayed. Another annoying thing is the console window is displayed on top of my windows form and i cant do any other operations on that form. I have set all properties like CreateNoWindow = true,

proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden

but still it shows the console window. even i have redirected output and errors to seperate stream but no luck.

Is there any other way to hide the Console window? Please help me out .

Here is the part of my code i used to execute sc command.

Process proc = new Process();
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
proc.StartInfo.FileName = "sc";
proc.StartInfo.Arguments = string.Format(@"\\SYS25 create MySvc binPath= C:\mysvc.exe");
proc.StartInfo.RedirectStandardError = false;
proc.StartInfo.RedirectStandardOutput = false;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.CreateNoWindow = true;
proc.Start();
proc.WaitForExit();

Answer

John Bartels picture John Bartels · Feb 8, 2013

I had a similar issue when attempting to start a process without showing the console window. I tested with several different combinations of property values until I found one that exhibited the behavior I wanted.

Here is a page detailing why the UseShellExecute property must be set to false.
http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.createnowindow.aspx

Under Remarks section on page:

If the UseShellExecute property is true or the UserName and Password properties are not null, the CreateNoWindow property value is ignored and a new window is created.

ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = fullPath;
startInfo.Arguments = args;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
startInfo.CreateNoWindow = true;

Process processTemp = new Process();
processTemp.StartInfo = startInfo;
processTemp.EnableRaisingEvents = true;
try
{
    processTemp.Start();
}
catch (Exception e)
{
    throw;
}