2014-02-27 31 views
0

我正在處理包含大量日誌消息的應用程序窗口。我需要過濾它們,並檢索那些只有這些mathches一些條件。我選擇遍歷它們的全部是TreeWalker,因爲在AutomationElement.GetAll()太貴(可能有數千條消息)後過濾了大量消息。TreeWalker從另一個窗口遍歷控件

List<AutomationElement> messages = new List<AutomationElement>(); 
    TreeWalker walker = new TreeWalker(new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.DataItem)); 
    AutomationElement row = walker.GetFirstChild(parentDatagrid); 
    while (row != null) 
    { 
     if (/*some condition*/) 
      messages.Add(row); 
     row = walker.GetNextSibling(row); 
    } 

這是我正在測試的控制層次結構的UISpy視圖。

Screenshot from UISpy

不料messages長度較大,實際的日誌消息計數。我查詢了額外的自動化元素是UISpy,發現這些元素是從另一個窗口中檢索到的(它們也符合條件ControlTypeProperty = ControlType.DataItem)。而且,這個窗口甚至屬於另一個應用程序。 TreeWalkerparentDatagrid範圍內完成搜索並繼續遍歷所有桌面層次結構。

當然,我希望只獲得datagrid的子元素。什麼可能導致這種奇怪的TreeWalker行爲?也許,我的代碼是錯誤的,但是我多次編寫了相同的代碼,並且它正常工作。

回答

0

事實上,我不能告訴你爲什麼TreeWalker會這麼做,因爲我從不使用TreeWalker進行導航。我只是用它來查找父母,孩子的,sibilings等。

我可以告訴你的是,我有使用下面的很好的經驗:

List<AutomationElement> messages = new List<AutomationElement>(); 
AutomationElement parentDatagrid;//your AE 

Condition yourCond = new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.DataItem)); 
AutomationElementCollection aECollection; 
aECollection= parentDatagrid.FindAll(TreeScope.Element | TreeScope.Descendants, yourCond); 
foreach (AutomationElement element in aECollection) 
{ 
    //whatever you like 
} 
當然

你必須要請注意TreeScope.Descendants,如果性能是一個問題。那麼你應該考慮TreeScope.Children,因爲後代在直接的孩子看着所有的子元素和孩子。

希望這有助於!

+0

感謝您的回覆。 TreeWalker有意用於導航,因爲它允許逐個遍歷控件,而無需像AutomationElement.FindAll()那樣預先加載所有控件。 – Grade

+0

只是爲了確保: 您是否還嘗試過使用TreeScope.Children而不是TreeScope.Descendants?我測試了一個示例應用程序,其中包含一些層次結構(大約30),總共大約250個元素,每個元素花費我大約0.3-0.6秒,使用TreeScope.Children的速度要快得多(大約爲0, 01-0,001) – Hansa

+0

如果您正在自動執行wpf控件,請閱讀以下[msdn-link](http://msdn.microsoft.com/zh-cn/library/ms788741(v = vs.110).aspx),否則,很抱歉... 「以下示例顯示了從列表中檢索指定項目的兩種方法,一種使用TreeWalker,另一種使用FindAll。 第一種技術對於Win32控件往往更快,但第二種技術對於Windows更快演示基礎(WPF)控件。「 – Hansa

0

當您創建自定義TreeWalker時,就像您所做的那樣,行爲將如您所述。使用TreeWalker.ControlViewWalker可能會更好,然後檢查每個檢索到的元素是否符合您的條件。

相關問題