我想要做的最终目标是将MMC(Microsoft管理控制台)计算机管理管理单元(compmgmt.msc)进程嵌入到Windows窗体中,或者将其视为模式弹出窗口的解决方法上菜单。

现在,我只是试图让mmc.exe本身正常运行,然后再尝试加载管理单元。问题的第一部分是mmc.exe进程几乎立即退出。

编辑: mmc.exe仅在应用程序构建为32位(我的计算机是64位)时立即退出。如果将应用程序构建为64位,则第一个进程将保留,这是预期的行为。
但是,对于为什么会发生奇怪的临时过程行为的原因,我仍然感到好奇。请注意,启动的临时mmc.exe进程是32位的,但是启动的最终mmc.exe是64位的。奇怪的。

以下代码将成功将iexplore.exe嵌入Windows窗体中,但无法嵌入mmc.exe
失败的原因是在调用p.WaitForInputIdle()时发生异常。



从错误消息中可以看到,该过程在几毫秒内退出,但是从用户的角度来看,MMC的GUI仍然作为与我启动的原始过程无关的独立过程弹出。

这意味着正在创建另一个mmc.exe进程,该进程似乎与创建的原始进程没有任何关系。

因此,问题是:为什么MMC进程立即关闭,而另一个MMC进程几乎立即打开?

相关的Windows Form代码,类似于this question

[DllImport("user32.dll")]
static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);

private void Form1_KeyPress(object sender, EventArgs e)
{
    /// Uncomment *one* of these:
    //Process p = Process.Start("mmc.exe");
    //Process p = Process.Start("iexplore.exe");
    Thread.Sleep(500);

    p.WaitForInputIdle();

    Console.WriteLine("MainWindowHandle: " + p.MainWindowHandle);
    Console.WriteLine("Handle: " + p.Handle);

    Thread.Sleep(5000);
    SetParent(p.MainWindowHandle, this.Handle);
}

相关,但是问题似乎更多是关于控制台GUI本身的关闭,而不是与某些基础进程的关闭相反,不允许进行编辑。
https://superuser.com/questions/194252/mmc-exe-starts-and-then-immediately-stops



随之而来的问题是,即使当我located the new mmc process that pops up时,它似乎也将MainWindowHandle设置为null possibly meaning Windows doesn't recognize it as having a GUI

解决此问题的方法很简单,即在创建“临时” mmc进程与等待新进程实际就绪之间添加 sleep (暂停)。注意process.WaitForInputIdle();没有等待足够长的时间。

对于可能遇到与我相同的麻烦的任何人:
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = Environment.SystemDirectory + "\\" + "mmc.exe";
startInfo.Arguments = "\"" + Environment.SystemDirectory + "\\compmgmt.msc\" /s";
Process tempProcess = Process.Start(startInfo);
tempProcess.WaitForExit();

Thread.Sleep(500); // Added pause!
// Better alternative is to use a while loop on (MainWindowHandle == null)
// with some sort of timeout

Process[] processes = Process.GetProcessesByName(Path.GetFileNameWithoutExtension(startInfo.FileName));
foreach (Process process in processes)
{
    // do what you want with the process
    Console.WriteLine("MainWindowHandle: " + process.MainWindowHandle);
    // Set Computer Management window on top
    SetWindowPos(process.MainWindowHandle, HWND_TOPMOST, 0, 0, 0, 0, TOPMOST_FLAGS);
    SetParent(process.MainWindowHandle, this.Handle);
    SetWindowLong(process.MainWindowHandle, GWL_STYLE, WS_VISIBLE);

    process.WaitForExit();
}

但主要问题是弄清楚为什么第一个MMC进程退出。

最佳答案

之所以退出,是因为可能需要使用不同的MMC位深度来运行管理单元。正如我现在刚刚学习的那样,管理单元可以是32位或64位。 Windows可能需要使用C:\Windows\SysWOW64\mmc.exe(1.34 MB(1,409,024字节))或使用C:\Windows\System32\mmc.exe(1.71 MB(1,802,240字节))重新启动管理单元。
https://docs.microsoft.com/en-us/previous-versions/windows/desktop/legacy/ms692753(v=vs.85)

因此,对我而言,当前的任务似乎是如何在启动管理单元之前发现该管理单元的位深度。

关于c# - MMC进程立即关闭,无法链接到Windows窗体,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47083917/

10-11 01:51