首页 > 解决方案 > 决定一个进程是否在同一个控制台中启动除了 UseShellExecute = false

问题描述

查看Start a process in the same console以及其他资源,听起来您唯一需要做的就是设置UseShellExecute为 false 才能让进程在与当前进程相同的控制台中启动。

但是,我发现这并不总是有效。例如,我创建了一个 NUnit 测试并从 Visual Studio 运行它:

[Test]
public void ConsoleTest()
{
            var p = new System.Diagnostics.Process();
            p.StartInfo = new System.Diagnostics.ProcessStartInfo(@"c:\windows\system32\netstat.exe", "-n")
            {
                UseShellExecute = false,
            };

            p.Start();
            var hasSameConsole = HasSameConsole(p.Id);
            Assert.IsFalse(p.HasExited, "process was still running when we did the console test");
            Assert.IsTrue(hasSameConsole); // this fails
}

private static bool HasSameConsole(int processId)
{
            uint processListCount = 1;
            uint[] processIdListBuffer;
            do
            {
                processIdListBuffer = new uint[processListCount];
                processListCount = GetConsoleProcessList(processIdListBuffer, processListCount);
            }
            while (processListCount > processIdListBuffer.Length);

            return processIdListBuffer.Take((int)processListCount)
                .Contains(checked((uint)processId));
}

[DllImport("kernel32.dll", SetLastError = true)]
public static extern uint GetConsoleProcessList(uint[] lpdwProcessList, uint dwProcessCount);

这种行为的原因是什么?

编辑:

为了确保当前进程有一个控制台,我添加了:

[DllImport("kernel32.dll", SetLastError = true)]
prviate static extern bool AllocConsole();

...

// before starting the child process
Assert.IsTrue(AllocConsole());

但是,我仍然没有看到子进程继承控制台。

标签: c#.netwindowsprocessconsole

解决方案


推荐阅读