このブログのコードを以下のように要約して使用しました。メイン ウィンドウ内に WinForm が表示されますが、ラベルに配置したサンプル テキストは表示されません。
[System.Windows.Markup.ContentProperty("Child")]
public class WinFormsHost : HwndHost
{
public WinFormsHost()
{
var form = new ChildForm();
Child = form;
}
private System.Windows.Forms.Form child;
public event EventHandler<ChildChangedEventArgs> ChildChanged;
public System.Windows.Forms.Form Child
{
get { return child; }
set
{
HwndSource ps = PresentationSource.FromVisual(this) as HwndSource;
if (ps != null && ps.Handle != IntPtr.Zero)
{
throw new InvalidOperationException("Cannot set the Child property after the layout is done.");
}
Form oldChild = child;
child = value;
OnChildChanged(oldChild);
}
}
private void CheckChildValidity()
{
if (child == null || child.Handle == IntPtr.Zero)
{
throw new ArgumentNullException("child form cannot be null");
}
}
public Boolean ShowCaption
{
get
{
CheckChildValidity();
return (GetWindowStyle(Child.Handle) & WindowStyles.WS_BORDER) == WindowStyles.WS_CAPTION;
}
set
{
if (child == null)
{
this.ChildChanged += delegate
{
if (value)
{
SetWindowStyle(Child.Handle, GetWindowStyle(Child.Handle) | WindowStyles.WS_CAPTION);
}
else
{
SetWindowStyle(Child.Handle, GetWindowStyle(Child.Handle) & ~WindowStyles.WS_CAPTION);
}
};
}
else
{
if (value)
{
SetWindowStyle(Child.Handle, GetWindowStyle(Child.Handle) | WindowStyles.WS_CAPTION);
}
else
{
SetWindowStyle(Child.Handle, GetWindowStyle(Child.Handle) & ~WindowStyles.WS_CAPTION);
}
}
}
}
protected override HandleRef BuildWindowCore(HandleRef hwndParent)
{
CheckChildValidity();
HandleRef childHwnd = new HandleRef(Child, child.Handle);
SetWindowStyle(childHwnd.Handle, WindowStyles.WS_CHILD | GetWindowStyle(childHwnd.Handle));
WindowsFormsHost.EnableWindowsFormsInterop();
System.Windows.Forms.Application.EnableVisualStyles();
SetParent(childHwnd.Handle, hwndParent.Handle);
return childHwnd;
}
}
と:
<Window x:Class="WinFormsHost"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
xmlns:cc="clr-namespace:XTime.Shell.WinformsHost"
Title="Hosting Form In WPF">
<cc:WinFormsHost ShowCaption="False">
<wf:Form/>
</cc:WinFormsHost>
</Window>