我有一个驻留在WindowsFormsHost中的WindowsFormsHost控件。这是我用来完成这个任务的XAML:
<Window x:Class="Forms.Address.MyWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Forms.Address"
xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
mc:Ignorable="d"
Title="New Window" Height="500" Width="720">
<Grid>
<WindowsFormsHost x:Name="host">
<local:MyFormsControl x:Name="genericName"/>
</WindowsFormsHost>
</Grid>
</Window>我想从WindowsFormsHost所在的窗口收听事件。这在Windows窗体中很简单,因为我可以使用FindForm方法获取控件所在的窗体。但是,由于明显的原因,当控件位于FindForm的内部时,WindowsFormsHost无法工作。我的控件的父控件是System.Windows.Forms.Integration.WinFormsAdapter,其父控件为null。
我的问题是:如何找到包含我的控件的窗口?
发布于 2017-05-19 13:51:44
我要感谢elgonzo,他建议我使用反射从WinFormsAdapter类获取字段。下面是我找到窗户的方法:
public static Window findParentWindow(Control control) {
WindowsFormsHost host = findWPFHost(control);
return Window.GetWindow(host);
}//FindParentWindow
private static WindowsFormsHost findWPFHost(Control control) {
if (control.Parent != null)
return findWPFHost(control.Parent);
else {
string typeName = "System.Windows.Forms.Integration.WinFormsAdapter";
if (control.GetType().FullName == typeName) {
Assembly adapterAssembly = control.GetType().Assembly;
Type winFormsAdapterType = adapterAssembly.GetType(typeName);
return (WindowsFormsHost)winFormsAdapterType.InvokeMember("_host", BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.Instance, null, control, new string[0], null);
} else
throw new Exception("The top parent of a control within a host should be a System.Windows.Forms.Integration.WinFormsAdapter, but that is not what was found. Someone should propably check this out.");
}//if
}//FindWPFHost我所做的是首先递归地找到WinFormsAdapter,然后使用反射从其中提取_host字段。这是WPF WindowsFormsHost对象,因此可以使用Window.GetWindow(host)找到它的窗口。
一个警告是,如果WindowsFormsHost是使用ElementHost放置在Windows中的,由于没有窗口,GetWindow将返回null。
发布于 2017-05-18 20:48:47
只需将属性添加到窗口和问题中,并在代码中传递其他窗口。这听起来是低科技的,你必须能够忍受妥协。不知道如何用100%的Xaml来完成这个任务。
如果您不喜欢这个,请将其与其他选项(winapi等)的适口性进行比较。可以由你说了算!
https://stackoverflow.com/questions/44055831
复制相似问题