0

我有一个混合了 WPF 和 Windows 窗体的旧应用程序。本质上,通过将 ElementHost 添加到 Windows 窗体,将 WPF 应用程序加载到 Windows 窗体应用程序中。然后,此 WPF 应用程序将 WPF 用户控件加载到它上面。嵌入在此 WPF 用户控件中的是旧版 Windows 控件(自定义浏览器控件),它最终派生自 System.Windows.Forms

有没有办法从代码中动态获取该控件的句柄?我们不知道控件在呈现时的名称。我们所知道的是控件的基本类型,正如我提到的,它源自 System.WIndows.Forms。

到目前为止,我看到的所有示例都讨论了如何动态发现最终成为 DependencyObject 的子对象。我还没有遇到一个示例来解释如何在 WPF 应用程序中以编程方式发现旧式 Windows 窗体控件。

4

2 回答 2

0

为了在 WPF 控件中托管 Winforms 控件,它必须使用WindowsFormsHost. WindowsFormsHost 源自DependencyObject. _ _

您必须WindowsFormsHost在 WPF 应用程序中找到该元素,然后才能访问Child包含该WebBrowser控件的属性。

伪代码:

var controlYoureLookingFOr = GiveMeAllChildren(WPFApp)
  .OfType<WindowsFormsHost>
  .First();

var browser = (WebBrowser.Or.Something)controlYoureLookingFOr.Child;
于 2015-01-13T11:21:26.270 回答
0

在这里完成答案是我添加的递归部分,以确保遍历整个窗口或父控件及其所有后代

   public static IEnumerable<T> FindAllChildrenByType<T>(this System.Windows.Forms.Control control)
    {
        IEnumerable<System.Windows.Forms.Control> controls = control.Controls.Cast<System.Windows.Forms.Control>();
        return controls
            .OfType<T>()
            .Concat<T>(controls.SelectMany<System.Windows.Forms.Control, T>(ctrl => FindAllChildrenByType<T>(ctrl)));
    }
    public static IEnumerable<T> FindVisualChildren<T>(this DependencyObject depObj) where T : DependencyObject
    {
        if (depObj != null)
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
            {
                DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
                if (child != null && child is T)
                {
                    yield return (T)child;
                }

                foreach (T childOfChild in FindVisualChildren<T>(child))
                {
                    yield return childOfChild;
                }
            }
        }
    }

然后,您可以将其用作

 var windowsFormHost = parentControl.FindVisualChildren<WindowsFormsHost>();
            foreach (var item in windowsFormHost)
            {
                var htmlcontrols = item.Child.FindAllChildrenByType<{sometypehere}
                foreach (var control in htmlcontrols)
                {
                }
             }
于 2015-01-16T06:07:08.020 回答