Start a process in the same console

前端 未结 2 1156
爱一瞬间的悲伤
爱一瞬间的悲伤 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());
        }           
    }
    

提交回复
热议问题