在同一控制台中启动进程

我可以在与调用程序相同的控制台中启动进程(使用C# Process.Start() )吗? 这样就不会创建新窗口,标准输入/输出/错误将与调用控制台应用程序相同。 我尝试设置process.StartInfo.CreateNoWindow = true; 但是该过程仍然在一个新窗口中开始(并在完成后立即关闭)。

除了设置UseShellExecute = false ,您不需要执行任何操作,因为Win32 CreateProcess函数的默认行为是控制台应用程序inheritance其父控制台,除非您指定CREATE_NEW_CONSOLE标志。

我尝试了以下程序:

 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(); } 

它给了我这个输出:

替代文字

您可以尝试重定向此进程的输出,然后将其打印在调用进程控制台上:

 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()); } } 

使用Exited事件和等待句柄的替代方法:

 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()); } }