private static object ExecuteWithDescendants(AutomationElement root, WithElementCallback callback)
{
var children = root.FindAll(TreeScope.Children, Condition.TrueCondition);
// Check descendants in breadth-first order (the assumption is that the required element
// is more likely to be closer to the root element).
var queue = new Queue(children);
while (queue.Count > 0) {
var child = (AutomationElement) queue.Dequeue();
var result = callback(child);
if (result != null)
return result;
// Queue all grand children for processing.
var grandChildren = child.FindAll(TreeScope.Children, Condition.TrueCondition);
foreach (AutomationElement grandChild in grandChildren)
queue.Enqueue(grandChild);
}
// None of the descendants matched, so return null.
return null;
}