views:

79

answers:

2

Can I start a process (using C# Process.Start()) in the same console as the calling program? This way no new window will be created and standard input/output/error will be the same as the calling console application. I tried setting process.StartInfo.CreateNoWindow = true; but the process still starts in a new window (and immediately closes after it finishes).

+6  A: 

You could try redirecting the output of this process and then printing it on the calling process console:

public class Program
{
    static void Main()
    {
        var psi = new ProcessStartInfo
        {
            FileName = @"c:\windows\system32\netstat.exe",
            Arguments = "-n",
            RedirectStandardOutput = true,
            UseShellExecute = false
        };
        var process = Process.Start(psi);
        while (!process.HasExited)
        {
            Thread.Sleep(100);
        }

        Console.WriteLine(process.StandardOutput.ReadToEnd());
    }
}

Alternative approach using the Exited event and a wait handle:

static void Main()
{
    using (Process p = new Process())
    {
        p.StartInfo = new ProcessStartInfo
        {
            FileName = @"netstat.exe",
            Arguments = "-n",                                        
            RedirectStandardOutput = true,
            UseShellExecute = false                    
        };
        p.EnableRaisingEvents = true;
        using (ManualResetEvent mre = new ManualResetEvent(false))
        {
            p.Exited += (s, e) => mre.Set();
            p.Start();
            mre.WaitOne();
        }

        Console.WriteLine(p.StandardOutput.ReadToEnd());
    }           
}
Darin Dimitrov
Any particular reason for looping with `Thread.Sleep` instead of listening for `Process.Exited` and synchronizing with a wait handle instead?
Fredrik Mörk
No, no particular reason, just being lazy, feel free to edit my answer to reflect this excellent suggestion.
Darin Dimitrov
Or you could just use `Process.WaitForExit` :)
Phil Devaney
+3  A: 

You shouldn't need to do anything other than set UseShellExecute = false, as the default behaviour for the Win32 CreateProcess function is for a console application to inherit its parent's console, unless you specify the CREATE_NEW_CONSOLE flag.

I tried the following program:

private static void Main()
{
    Console.WriteLine( "Hello" );

    var p = new Process();
    p.StartInfo = new ProcessStartInfo( @"c:\windows\system32\netstat.exe", "-n" ) 
        {
            UseShellExecute = false
        };

    p.Start();
    p.WaitForExit();

    Console.WriteLine( "World" );
    Console.ReadLine();
}

and it gave me this output:

alt text

Phil Devaney