C# Windowless Process

Wednesday Nov 13, 2019

I was playing with C# and tyring to get an FCGI process to run on a Windows machine without a Window being created.

This book was really helpful: C++/CLI Primer: For .NET Development

This proved to be much trickier than it sounds. Here is what I found.

System.Diagnostics.Process.Start()

Having issues getting the System.Diagnostics.Process.Start(…) method to run a process and hide the window. I tried all sorts of things including:

String proc = "d:\\php-5.6.8\\php-cgi.exe";
String args = "-b localhost:9000";
ProcessStartInfo psi = new ProcessStartInfo();

psi.WindowStyle = ProcessWindowStyle.Hidden;
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;
psi.UseShellExecute = false;
psi.CreateNoWindow = true;

p = new Process();
p.StartInfo = psi;
p = Process.Start(proc, args);

I finally found this on the MSDN site at https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.processstartinfo.createnowindow?redirectedfrom=MSDN&view=netframework-4.8#System_Diagnostics_ProcessStartInfo_CreateNoWindow :

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

I’m using the method:

    Start(String command, String arguments)
 

However, there is another method that is:

    Start(String command, String arguments, String user, SecureString password, String domain)
 

So, if we change the last line from:

    p = Process.Start(proc, args);
 

to:

    p = Process.Start(proc, args, null, null, null);
 

it works! Here is the complete code listing:

    class Program
    {
    Process p;
       String proc = "d:\\php-5.6.8\\php-cgi.exe";
    String args = "-b localhost:9000";
    
    public Program(){
    }
    
    public void RunProgram(){
        Console.Write("Running: " + proc);
        
        ProcessStartInfo psi = new ProcessStartInfo();
        psi.WindowStyle = ProcessWindowStyle.Hidden;
        psi.RedirectStandardOutput = true;
        psi.RedirectStandardError = true;
        psi.UseShellExecute = false;
        psi.CreateNoWindow = true;
        
        p = new Process();
        p.StartInfo = psi;
        p = Process.Start(proc, args, null, null, null);
        
        Console.Write("Process started...");
    }
    
    public void Terminate(){
        p.Kill();
        p.Close();
        p.Dispose();
    }
    
    public static void Main(string[] args)
    {
        Console.WriteLine("Hello World!");
        
        Program myp = new Program();
        myp.RunProgram();
        
        Console.Write("Press any key to continue . . . ");
        Console.ReadKey(true);
        myp.Terminate();
    }
}

That’s it. FWIW - here is a recommendation for a C# development book from Amazon: C++/CLI Primer: For .NET Development