代码之家  ›  专栏  ›  技术社区  ›  Steven Evans

未出现子进程窗口

  •  -1
  • Steven Evans  · 技术社区  · 7 年前

    我试图从显示控制台的c#console应用程序中创建一个子进程。我尝试了以下操作,但没有出现窗口。

            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();
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Krish    7 年前

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

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

    我们保留了默认值 使用ShellExecute ,即 true

    让我们翻转 使用ShellExecute 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();
            }
        }
    }