有没有办法将程序用作 MDI 子窗口。我正在考虑拥有一个可以有多个子窗口的主 MDI 父窗口,其中一些将是程序(.exe 文件)。
蒂姆
实际上有一个非常简单的方法可以做到这一点。
首先,您需要在表单中添加一个面板。该面板将用于“托管”应用程序。
接下来,您需要将“System.Runtime.InteropServices”和“System.Diagnostics”命名空间添加到您的命名空间:csharp
using System.Diagnostics;
using System.Runtime.InteropServices;
现在,我们需要设置我们的 WinAPI 函数:
[DllImport("user32.dll")]
static extern IntPtr SetParent(IntPtr hwndChild, IntPtr hwndNewParent);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
static extern IntPtr SendMessage(IntPtr hWnd, Int32 Msg, Int32 wParam, Int32 lParam);
现在,在按钮单击事件中,启动进程,并将其设置为面板的父级。在这个例子中,我将使用记事本:
// Create a new process
Process proc;
// Start the process
proc = Process.Start("notepad.exe");
proc.WaitForInputIdle();
// Set the panel control as the application's parent
SetParent(proc.MainWindowHandle, this.panel1.Handle);
// Maximize application
SendMessage(proc.MainWindowHandle, 274, 61488, 0);
几年前我实现了类似的东西(如果我没记错的话,基于.NET Framework 1.1)。该实施的关键要素是:
Form
类,它公开了一些特定的功能,例如用于提取调用 UI 的用户命令的接口。Activator.CreateInstance
),从表单边框中剥离并嵌入到容器中(在我们的例子中是 a TabPage
in a TabControl
,在你的例子中很可能是一个“空”的 MDI Child申请表中的表格)。我认为这一切都很好(我实际上认为该框架仍在为其创建的公司内维护和使用)。
您可能需要关注内存管理。例如,由于无法卸载程序集,如果需要,您需要将外部程序集加载到单独的 AppDomain 中。还要注意在加载子窗口 UI 时动态附加的任何事件处理程序,以便在卸载 UI 时正确分离它们。
导入InteropServices
和Threading
命名空间
using System.Runtime.InteropServices;
using System.Threading;
导入SetParent
自user32.dll
[DllImport("user32.dll")]
static extern IntPtr SetParent(IntPtr child,IntPtr parent);
创建一个新进程并使用它使其成为我们表单的 MDI 子进程SetParent
Process proc;
// Start the process
proc = Process.Start("calc.exe");
proc.WaitForInputIdle();
Thread.Sleep(500);
// Set the panel control as the application's parent
SetParent(proc.MainWindowHandle, this.panel1.Handle);