This documentation is archived and is not being maintained.

Navigate Among UI Automation Elements with TreeWalker

This topic contains example code that shows how to navigate among Microsoft UI Automation elements by using the TreeWalker class.

The following example uses GetParent to walk up the Microsoft UI Automation tree until it finds the root element, or desktop. The element just below that is the parent window of the specified element.

/// <summary> 
/// Retrieves the top-level window that contains the specified UI Automation element. 
/// </summary> 
/// <param name="element">The contained element.</param>
/// <returns>The containing top-level window element.</returns> 
private AutomationElement GetTopLevelWindow(AutomationElement element)
    TreeWalker walker = TreeWalker.ControlViewWalker;
    AutomationElement elementParent;
    AutomationElement node = element;
    if (node == elementRoot) return node;
        elementParent = walker.GetParent(node);
        if (elementParent == AutomationElement.RootElement) break;
        node = elementParent;
    while (true);
    return node;

The following example uses GetFirstChild and GetNextSibling to create a TreeView that shows an entire subtree of Microsoft UI Automation elements that are in the control view and that are enabled.

/// <summary> 
/// Walks the UI Automation tree and adds the control type of each enabled control  
/// element it finds to a TreeView. 
/// </summary> 
/// <param name="rootElement">The root of the search on this iteration.</param>
/// <param name="treeNode">The node in the TreeView for this iteration.</param>
/// <remarks> 
/// This is a recursive function that maps out the structure of the subtree beginning at the 
/// UI Automation element passed in as rootElement on the first call. This could be, for example, 
/// an application window. 
/// CAUTION: Do not pass in AutomationElement.RootElement. Attempting to map out the entire subtree of 
/// the desktop could take a very long time and even lead to a stack overflow. 
/// </remarks> 
private void WalkEnabledElements(AutomationElement rootElement, TreeNode treeNode)
    Condition condition1 = new PropertyCondition(AutomationElement.IsControlElementProperty, true);
    Condition condition2 = new PropertyCondition(AutomationElement.IsEnabledProperty, true);
    TreeWalker walker = new TreeWalker(new AndCondition(condition1, condition2));
    AutomationElement elementNode = walker.GetFirstChild(rootElement);
    while (elementNode != null)
        TreeNode childTreeNode = treeNode.Nodes.Add(elementNode.Current.ControlType.LocalizedControlType);
        WalkEnabledElements(elementNode, childTreeNode);
        elementNode = walker.GetNextSibling(elementNode);