【问题标题】:How to find in code the parent Window or WinForm of a WPF control?如何在代码中找到 WPF 控件的父窗口或 WinForm?
【发布时间】:2010-06-16 16:05:16
【问题描述】:

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

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

【问题讨论】:

    标签: wpf interop


    【解决方案1】:

    刚刚想通了!

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

    【讨论】:

      【解决方案2】:
      [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.

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-08-04
        • 1970-01-01
        • 1970-01-01
        • 2015-12-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多