我有一种情况,我需要找到承载WPF控件的父窗口或WinForm。无论情况如何,我都需要获得父窗口或WinForm的句柄。如何在代码中找到WPF控件的父窗口或WinForm?
问题是什么时候使用ElementHost将WPF控件托管在WinForm中。我如何从WPF控件找到托管WinForm的Handle。
我有一种情况,我需要找到承载WPF控件的父窗口或WinForm。无论情况如何,我都需要获得父窗口或WinForm的句柄。如何在代码中找到WPF控件的父窗口或WinForm?
问题是什么时候使用ElementHost将WPF控件托管在WinForm中。我如何从WPF控件找到托管WinForm的Handle。
只是想通了!
var presentationSource = (HwndSource)PresentationSource.FromVisual(child);
var parentHandle = presentationSource.Handle;
[DllImport("user32.dll")]
public static extern int GetParent(int hwnd);
public int GetParentWindowHandle(Visual child)
{
HwndSource presentationSource = (HwndSource)PresentationSource.FromVisual(child);
int parentHandle = presentationSource.Handle.ToInt32();
int handle = parentHandle;
while (parentHandle != 0)
{
handle = parentHandle;
parentHandle = ApplicationHelperInterop.GetParent(parentHandle);
}
return handle;
}
然后,您可以遍历集合System.Windows.Forms.Application.OpenForms
找到对应于上述GetParentWindowHandle方法的返回值一个WinForm。
Alex D.