2016-03-04 136 views
1

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

问题是它永远不会到else语句并且永远不会结束。所以我认为它根本找不到这个元素。

这里是元素突出,我试图用得到:

screenshot from inspect

感谢

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; 
    } 
+0

你没不提哪种方式不起作用。什么都没有发生?它是否会抛出异常?如果是这样,请提供例外信息。 –

+0

它永远不会到else语句,永不结束。所以我认为它根本找不到这个元素。谢谢 – Samy

+0

好吧,不要忽略GetElement()的返回值。如果它不为空,它当然会是你正在寻找的那个。 –

回答

0

树遍历将是这项任务更好。

用例:

// 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; 
} 
+0

非常感谢您的回答。这是获得元素的一个好方法。但是,它对我来说仍然是空的。控制是嵌入式的,我不明白为什么它会找到它。我在原始文章中添加了一个截图,为您提供一个主意。 – Samy

+0

您首先需要点击“Previous Location”,以便创建“Address”控件。 –

+0

对不起,我不明白你的答案@ florentbr。我应该尝试首先获取“地址”组合框吗?谢谢, – Samy