c# - 决定一个进程是否在同一个控制台中启动除了 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());
但是,我仍然没有看到子进程继承控制台。
解决方案
推荐阅读
- angular - 组件不是任何 NgModule 的一部分,或者该模块尚未导入您的模块(延迟加载)
- wpf - 不要触发 RelayCommand
- android - Livedata 和许多观察者和实例
- c# - C# HttpClient 和 Windows 身份验证:无法访问已关闭的流
- python - 如何使用 python3 在某些条件下读取列表?
- sas - 从单个数据行创建饼图 - SAS 分析
- python - Python字典:填充字典的函数覆盖同一函数的早期调用
- angular - 具有相同 ngModel 的多个文本框
- c# - 显示没有错误,但在 RedirectToAction 之后仍然没有加载视图
- c# - 如何使用 linq 将列数据移动到同一行中的另一列