Search code examples
c#windowsautomationui-automationautomationelement

Using Windows.Automation, can I locate an AutomationElement by regex?


I have an object tree that has row objects within a table parent. I'm attempting to put all these rows into an AutomationElementCollection

AutomationElementCollection asdf = ParentTableObj.FindAll
     (
     TreeScope.Children,
     new PropertyCondition
          (
          AutomationElement.NameProperty,
          "I want to use regex here"
          )
     );

All of the rows' AutomationElement.NameProperty contains the string "row". However, they are variations of that string - e.g. "Row1", "Row2", "TopRow", ...

It seems like I may be missing something since the FindAll method allows you to define the TreeScope and find any AutomationElement, which matches the provided Condition parameter. I just want my condition to be unrestricted since I can already control the find scope by TreeScope.


Solution

  • //Example :
    AutomationElement element = FindFirstDescendant( 
        AutomationElement.FromHandle(windows_hWnd), 
        (ele)=>Regex.IsMatch( ele.Current.Name, pattern)
    );
    
    //The generic method to find a descendant element:
    public static AutomationElement FindFirstDescendant(AutomationElement element, Func<AutomationElement, bool> condition) {
        var walker = TreeWalker.ControlViewWalker;
        element = walker.GetFirstChild(element);
        while (element != null) {
            if (condition(element))
                return element;
            var subElement = FindFirstDescendant(element, condition);
            if (subElement != null)
                return subElement;
            element = walker.GetNextSibling(element);
        }
        return null;
    }