您想要做的是完全可能的,但它确实存在一些错误,所以不要指望一帆风顺。您需要做的是创建一个继承自HwndHost 并覆盖BuildWindowCore() 方法的类。请参阅 Microsoft 的示例,地址为 http://msdn.microsoft.com/en-us/library/ms752055.aspx
在上面的示例中,它们为您提供了能够在 WPF 表单中放置 Win32 控件的概念,但您可以使用相同的体系结构将您创建的记事本进程的 MainWindowhandle 加载到边框的子进程中.像这样:
protected override HandleRef BuildWindowCore(HandleRef hwndParent)
{
ProcessStartInfo psi = new ProcessStartInfo("notepad.exe");
psi.WindowStyle = ProcessWindowStyle.Minimized;
_process = Process.Start(psi);
_process.WaitForInputIdle();
// The main window handle may be unavailable for a while, just wait for it
while (_process.MainWindowHandle == IntPtr.Zero)
{
Thread.Yield();
}
IntPtr notepadHandle = _process.MainWindowHandle;
int style = GetWindowLong(notepadHandle, GWL_STYLE);
style = style & ~((int)WS_CAPTION) & ~((int)WS_THICKFRAME); // Removes Caption bar and the sizing border
style |= ((int)WS_CHILD); // Must be a child window to be hosted
SetWindowLong(notepadHandle, GWL_STYLE, style);
SetParent(notepadHandle, hwndParent.Handle);
this.InvalidateVisual();
HandleRef hwnd = new HandleRef(this, notepadHandle);
return hwnd;
}
请记住,您需要从 User32.dll 中导入一些函数才能设置窗口样式和设置父窗口句柄:
[DllImport("user32.dll")]
private static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
[DllImport("user32.dll", SetLastError = true)]
private static extern int GetWindowLong(IntPtr hWnd, int nIndex);
[DllImport("user32")]
private static extern IntPtr SetParent(IntPtr hWnd, IntPtr hWndParent);
还要确保您包括:
using System.Windows.Interop;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
这是我在论坛上的第一个答案,所以如果它需要一些工作,请告诉我。也可以参考Hosting external app in WPF window,但不要担心 DwayneNeed 的东西。正如您在上面的代码中看到的那样,只需使用 SetParent() 即可。如果您尝试将应用程序嵌入标签页中,请小心。在那里你会遇到一些乐趣。