How to Walk the UI Automation Tree
This topic contains example code that shows how to use the IUIAutomationTreeWalker interface to walk through and examine the elements in the Microsoft UI Automation tree. It discusses the following topics:
Walking through Descendants of an Element
The following code example is a recursive function that walks through all the descendants of a UI element and displays their control types in a hierarchical list.
// CAUTION: Do not pass in the root (desktop) element. Traversing the entire subtree
// of the desktop could take a very long time and even lead to a stack overflow.
void ListDescendants(IUIAutomationElement* pParent, int indent)
{
if (pParent == NULL)
return;
IUIAutomationTreeWalker* pControlWalker = NULL;
IUIAutomationElement* pNode = NULL;
g_pAutomation->get_ControlViewWalker(&pControlWalker);
if (pControlWalker == NULL)
goto cleanup;
pControlWalker->GetFirstChildElement(pParent, &pNode);
if (pNode == NULL)
goto cleanup;
while (pNode)
{
BSTR desc;
pNode->get_CurrentLocalizedControlType(&desc);
for (int x = 0; x <= indent; x++)
{
std::wcout << L" ";
}
std::wcout << desc << L"\n";
SysFreeString(desc);
ListDescendants(pNode, indent+1);
IUIAutomationElement* pNext;
pControlWalker->GetNextSiblingElement(pNode, &pNext);
pNode->Release();
pNode = pNext;
}
cleanup:
if (pControlWalker != NULL)
pControlWalker->Release();
if (pNode != NULL)
pNode->Release();
return;
}
Walking through Ancestor Elements
The following code example is a function that walks through the ancestors of an element to identify the parent element. This is useful when you need to identify the parent window of a control. The function returns NULL for top-level elements; that is, elements whose parent is the desktop.
IUIAutomationElement* GetContainingWindow(IUIAutomationElement* pChild)
{
if (pChild == NULL)
return NULL;
IUIAutomationElement* pDesktop = NULL;
HRESULT hr = g_pAutomation->GetRootElement(&pDesktop);
if (FAILED(hr))
return NULL;
BOOL same;
g_pAutomation->CompareElements(pChild, pDesktop, &same);
if (same)
{
pDesktop->Release();
return NULL; // No parent, so return NULL.
}
IUIAutomationElement* pParent = NULL;
IUIAutomationElement* pNode = pChild;
// Create the treewalker.
IUIAutomationTreeWalker* pWalker = NULL;
g_pAutomation->get_ControlViewWalker(&pWalker);
if (pWalker == NULL)
goto cleanup;
// Walk up the tree.
while (TRUE)
{
hr = pWalker->GetParentElement(pNode, &pParent);
if (FAILED(hr) || pParent == NULL)
{
break;
}
g_pAutomation->CompareElements(pParent, pDesktop, &same);
if (same)
{
pDesktop->Release();
pParent->Release();
pWalker->Release();
// Reached desktop, so return next element below it.
return pNode;
}
if (pNode != pChild) // Do not release the in-param.
pNode->Release();
pNode = pParent;
}
cleanup:
if ((pNode != NULL) && (pNode != pChild))
pNode->Release();
if (pDesktop != NULL)
pDesktop->Release();
if (pWalker != NULL)
pWalker->Release();
if (pParent != NULL)
pParent->Release();
return NULL;
}
Related topics