使用 HwndHost 在 WPF 中托管外部窗口的正确方法

Mik*_*e G 6 c# wpf hwndhost

我想在我的 WPF 应用程序中托管一个外部进程的窗口。我是这样推导的HwndHost

    class HwndHostEx : HwndHost
    {
        [DllImport("user32.dll")]
        static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);

        private IntPtr ChildHandle = IntPtr.Zero;

        public HwndHostEx(IntPtr handle)
        {
            this.ChildHandle = handle;
        }

        protected override System.Runtime.InteropServices.HandleRef BuildWindowCore(System.Runtime.InteropServices.HandleRef hwndParent)
        {
            HandleRef href = new HandleRef();

            if (ChildHandle != IntPtr.Zero)
            {
                SetParent(this.ChildHandle, hwndParent.Handle);
                href = new HandleRef(this, this.ChildHandle);
            }

            return href;
        }

        protected override void DestroyWindowCore(System.Runtime.InteropServices.HandleRef hwnd)
        {

        }
    }
Run Code Online (Sandbox Code Playgroud)

并像这样使用它:

 HwndHostEx host = new HwndHostEx(handle);
 this.PART_Host.Child = host;
Run Code Online (Sandbox Code Playgroud)

handle我想托管的外部窗口的句柄在哪里,是PART_Host我的 WPF 窗口内的边框:

<StackPanel UseLayoutRounding="True"
        SnapsToDevicePixels="True"
        Background="Transparent">
        <Border Name="PART_Host" />
...
Run Code Online (Sandbox Code Playgroud)

这给了我一个例外:

Hosted HWND must be a child window.
Run Code Online (Sandbox Code Playgroud)

抱歉,我缺乏知识,但是在 WPF 应用程序中托管外部窗口的正确方法是什么?

小智 6

在调用“SetParent”之前执行以下操作:

public const int GWL_STYLE = (-16);
public const int WS_CHILD = 0x40000000;

SetWindowLong(this.ChildHandle, GWL_STYLE, WS_CHILD);
Run Code Online (Sandbox Code Playgroud)