如何在代码中找到WPF控件的父窗口或WinForm?

时间:2010-06-16 16:05:16

标签: wpf interop

我有一种情况需要找到托管WPF控件的父窗口或WinForm。无论情况如何,我都需要得到父窗口或WinForm的句柄。

问题是当使用ElementHost在WinForm中托管WPF控件时。如何从WPF控件中找到托管WinForm的句柄。

2 个答案:

答案 0 :(得分:3)

刚想通了!

var presentationSource = (HwndSource)PresentationSource.FromVisual(child);
var parentHandle = presentationSource.Handle;

答案 1 :(得分:1)

[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。

相关问题