代码之家  ›  专栏  ›  技术社区  ›  Trainee4Life

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

  •  4
  • Trainee4Life  · 技术社区  · 16 年前

    在这种情况下,我需要找到承载WPF控件的父窗口或WinForm。我需要获得父窗口或WinForm的句柄,不管是什么情况。

    问题在于,当wpf控件使用elementhost托管在winform中时。如何从WPF控件中找到宿主WinForm的句柄。

    2 回复  |  直到 15 年前
        1
  •  3
  •   Trainee4Life    16 年前

    我想明白了!

    var presentationSource = (HwndSource)PresentationSource.FromVisual(child);
    var parentHandle = presentationSource.Handle;
    
        2
  •  1
  •   Alexander    15 年前
    [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。

    亚历克斯D