UIAutomation won't retrieve children of an element

August picture August · Jan 6, 2013 · Viewed 9.5k times · Source

I can see that an element with specific Automation ID has children in the Inspect tool:

Inspect screenshot

But when I try to retrieve them like this:

AutomationElement aPane = mainWindow.FindFirst(TreeScope.Subtree, new PropertyCondition(AutomationElement.AutomationIdProperty, "8264"));
AutomationElementCollection theChildren = aPane.FindAll(TreeScope.Subtree, Condition.TrueCondition);

The aPane element is retrieved correctly, but theChildren element is empty. Any ideas what went wrong?

Answer

Mike Zboray picture Mike Zboray · Jan 6, 2013

On rare occasions I've found that the Find* calls don't find all automation objects. The only consistent case I've seen with this that WPF TextBlock controls, when in a data template, won't be found by those calls. In these cases, you can try the RawViewWalker which is probably closer to what Inspect is doing internally.

public static IEnumerable<AutomationElement> FindInRawView(this AutomationElement root)
{
    TreeWalker rawViewWalker = TreeWalker.RawViewWalker;
    Queue<AutomationElement> queue = new Queue<AutomationElement>();
    queue.Enqueue(root);
    while (queue.Count > 0)
    {
       var element = queue.Dequeue();
       yield return element;

       var sibling = rawViewWalker.GetNextSibling(element);
       if (sibling != null)
       {
          queue.Enqueue(sibling);
       }

       var child = rawViewWalker.GetFirstChild(element);
       if (child != null)
       {
          queue.Enqueue(child);
       }
    }
}