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

标签 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)
        {

        }
    }

并像这样使用它:

 HwndHostEx host = new HwndHostEx(handle);
 this.PART_Host.Child = host;

其中 handle 是我要托管的外部窗口的句柄,PART_Host 是我的 WPF 窗口内的边框:

<StackPanel UseLayoutRounding="True"
        SnapsToDevicePixels="True"
        Background="Transparent">
        <Border Name="PART_Host" />
...

这给了我一个异常(exception):

Hosted HWND must be a child window.

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

最佳答案

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

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

SetWindowLong(this.ChildHandle, GWL_STYLE, WS_CHILD);

关于c# - 使用 HwndHost 在 WPF 中托管外部窗口的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30186930/

相关文章:

c# - 工具提示闪烁。

wpf - 从 View 模型打开新窗口

c# - WPF ListView 中的多维绑定(bind)

.net - 如何将 Win32 鼠标消息转换为 WPF 鼠标事件?

c# - 如何在 C# 中实现 'Lucky Draw' 功能?

c# - .NET 平台标准中有哪些平台?

c# - 错误 "System.Xml.Linq.XDocument' 不包含定义是什么意思?

wpf - 对齐堆栈面板中的项目?

.net - 强制初始化 HwndHost