决定进程是否在同一控制台中启动的过程取决于UseShellExecute = false

时间:2019-04-24 02:19:36

标签: c# .net windows process console

看看Start a process in the same console以及其他资源,这听起来像您需要做的唯一一件事,就是使一个进程在同一控制台中启动,而当前进程是将UseShellExecute设置为错误。

但是,我发现这并不总是有效。例如,我创建了一个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());

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

0 个答案:

没有答案