子进程 window 未出现

child process window not appearing

我正在尝试从显示控制台的 c# 控制台应用程序创建子进程。我尝试了以下但没有 window 出现。

        ProcessStartInfo = new ProcessStartInfo(name)
        {
            UseShellExecute = false,
            RedirectStandardError = true,
            RedirectStandardOutput = true,
            WindowStyle = ProcessWindowStyle.Maximized,
            CreateNoWindow = false,
            ErrorDialog = false
        };

        if (args != null)
        {
            ProcessStartInfo.Arguments = args;
        }

        if (workingDirectory != null)
        {
            ProcessStartInfo.WorkingDirectory = workingDirectory;
        }

        Process = new Process {EnableRaisingEvents = true, StartInfo = ProcessStartInfo};
        Process.Start();

在父控制台中 运行 子进程的正确方法是设置 UseShellExecute 属性 of ProcessStartInfo class。让我们考虑一个执行时间命令的例子。为什么是时间?因为它从标准输入读取。这样你就会知道它使用的是哪个控制台。

public class Program
{
    public static void Main(string[] args)
    {
        var processInfo = new ProcessStartInfo
        {
            FileName = "cmd.exe",
            Arguments = "/c time"
        };

        Console.WriteLine("Starting child process...");
        using (var process = Process.Start(processInfo))
        {
            process.WaitForExit();
        }
    }
}

我们保留了 UseShellExecute 的默认值,即 true。这意味着 shell 将用于子进程。使用 shell 意味着将创建一个新控制台。

让我们将 UseShellExecute 的值翻转为 false

public class Program
{
    public static void Main(string[] args)
    {
        var processInfo = new ProcessStartInfo
        {
            UseShellExecute = false, // change value to false
            FileName = "cmd.exe",
            Arguments = "/c time"
        };

        Console.WriteLine("Starting child process...");
        using (var process = Process.Start(processInfo))
        {
            process.WaitForExit();
        }
    }
}