Start a process in the same console

前端 未结 2 1148
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-05 04:46

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/er

相关标签:
2条回答
  • 2020-12-05 04:57

    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());
        }           
    }
    
    0 讨论(0)
  • 2020-12-05 05:21

    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

    0 讨论(0)
提交回复
热议问题