在同一控制台中启动进程

Lou*_*hys 29 c# console process

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

Phi*_*ney 47

您不需要执行除set之外的任何操作UseShellExecute = false,因为Win32 CreateProcess函数的默认行为是控制台应用程序继承其父控制台,除非您指定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();
}
Run Code Online (Sandbox Code Playgroud)

它给了我这个输出:

替代文字


Dar*_*rov 9

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

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());
    }
}
Run Code Online (Sandbox Code Playgroud)

使用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());
    }           
}
Run Code Online (Sandbox Code Playgroud)

  • 或者你可以使用`Process.WaitForExit` :) (2认同)