在这里完成答案是我添加的递归部分,以确保遍历整个窗口或父控件及其所有后代
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)
{
}
}