2016-03-04 134 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