WPF Hwnd窗口互操作系列
第一章 嵌入Hwnd窗口
第二章 嵌入WinForm控件
第三章 嵌入WPF控件(本章)
第四章 嵌入外部程序
第五章 底部嵌入HwndHost
文章目录
前言
通过前面的章节我们了解到了如何嵌入Hwnd窗口以及WinForm控件,但是嵌入的控件存在覆盖wpf控件的情况,嵌入控件上面无法显示王鹏飞控件,对UI的布局有一定的影响。本文提供一种解决方法,
将wpf控件通过HwndHost的方式嵌入到wpf界面中,以实现HwndHost控件上显示wpf控件的功能。
一、如何实现?
1、继承HwndHost
和其他嵌入方式一样,需要先继承HwndHost。
public class WpfElementHost : HwndHost
2、添加Content属性
添加一个Content属性,提供给xaml使用。这个Content属性就是需要嵌入的wpf控件。
[ContentProperty("Content")]
public class WpfElementHost : HwndHost
{
public UIElement Content
{
get {
return (UIElement)GetValue(ContentProperty); }
set {
SetValue(ContentProperty, value); }
}
public static readonly DependencyProperty ContentProperty =
DependencyProperty.RegisterAttached("Content", typeof(UIElement), typeof(WpfElementHost), new PropertyMetadata(null));
}
3、创建wpf窗口并设置Content
实现抽象方法窗口wpf窗口,这里参考第一章的嵌入wpf窗口,以及给窗口设置Content属性。
protected override HandleRef BuildWindowCore(HandleRef hwndParent)
{
var window = Content is Window ? Content as Window : new Window {
WindowStyle = WindowStyle.None, ResizeMode = ResizeMode.NoResize, Focusable = false, Width = 0, Height = 0, ShowInTaskbar = false, ShowActivated = false, Background = Brushes.Transparent, Content = Content, AllowsTransparency = true };
var hwnd = new WindowInteropHelper(window).EnsureHandle();
SetWindowLong(hwnd, GWL_STYLE, GetWindowLong(hwnd, GWL_STYLE) | WS_CHILD);
User32.SetParent(hwnd, hwndParent.Handle);
window!.Show();
return new HandleRef(this, hwnd);
}