C# 递归,用于在打开的对话框中查找自动化元素

本文关键字:对话框 查找 自动化 元素 递归 用于 | 更新日期: 2023-09-27 18:37:23

我试图在单击下载按钮后浏览到文件。但是我虽然编写了一个递归函数,该函数使用 AutomationElement 库在任何窗口中查找控件,因此希望我可以在打开的对话框窗口中找到嵌套的控件。此功能现在不起作用。请让我知道这里的问题在哪里,或者如果您有任何建议,请告诉我。

问题是它永远不会到达 else 语句,也永远不会结束。所以我认为它根本没有找到元素。

这是我尝试使用的突出显示的元素:

来自检查的屏幕截图

谢谢

 private AutomationElement GetElement(AutomationElement element, Condition conditions, string className)
    {
        AutomationElement boo = null;
        foreach (AutomationElement c in element.FindAll(TreeScope.Subtree, Automation.ControlViewCondition))
        {
            var child = c;
            if (c.Current.ClassName.Contains(className) == false)
            {
                GetElement(child, conditions, className);   
             }
            else
            {
                boo = child.FindFirst(TreeScope.Descendants, conditions);
            }
        }
        return boo;
    }

C# 递归,用于在打开的对话框中查找自动化元素

树行者更适合这项任务。

使用示例:

// find a window
var window = GetFirstChild(AutomationElement.RootElement,
    (e) => e.Name == "Calculator");
// find a button
var button = GetFirstDescendant(window,
    (e) => e.ControlType == ControlType.Button && e.Name == "9");
// click the button
((InvokePattern)button.GetCurrentPattern(InvokePattern.Pattern)).Invoke();

使用委托递归查找后代元素的函数:

public static AutomationElement GetFirstDescendant(
    AutomationElement root, 
    Func<AutomationElement.AutomationElementInformation, bool> condition) {
    var walker = TreeWalker.ControlViewWalker;
    var element = walker.GetFirstChild(root);
    while (element != null) {
        if (condition(element.Current))
            return element;
        var subElement = GetFirstDescendant(element, condition);
        if (subElement != null)
            return subElement;
        element = walker.GetNextSibling(element);
    }
    return null;
}

查找具有委托的子元素的函数:

public static AutomationElement GetFirstChild(
    AutomationElement root,
    Func<AutomationElement.AutomationElementInformation, bool> condition) {
    var walker = TreeWalker.ControlViewWalker;
    var element = walker.GetFirstChild(root);
    while (element != null) {
        if (condition(element.Current))
            return element;
        element = walker.GetNextSibling(element);
    }
    return null;
}