title: WPF UI Automation - AutomationElement.FindFirst fails when there are lots of elements
body: <p>We've got some automated UI tests for our WPF app (.NET 4); these test use the <a href="http://msdn.microsoft.com/en-us/library/ms747327.aspx" rel="nofollow noreferrer">UI Automation</a> API's.</p>
  
  <p>We call <a href="http://msdn.microsoft.com/en-us/library/system.windows.automation.automationelement.findfirst.aspx" rel="nofollow noreferrer">AutomationElement.FindFirst</a> to find a target element, and then interact with it.</p>
  
  <p>Example (pseudocode):</p>
  
  <pre><code>var nameEquals = new PropertyCondition(AutomationElement.NameProperty, "OurAppWindow");
  var appWindow = DesktopWindow.FindFirst(TreeScope.Children, nameEquals);
  // this succeeds
  
  var idEquals = new PropertyCondition(AutomationElement.AutomationIdProperty, "ControlId");
  var someItem = appWindow.FindFirst(TreeScope.Descendants, idEquals);
  // this suceeds sometimes, and fails sometimes!
  </code></pre>
  
  <p>The problem is, the <code>appWindow.FindFirst</code> will sometimes fail and return null, even when the element is present. I've written a helper function which walks the UI automation tree manually and prints it out, and the element with the correct ID is present in all cases.</p>
  
  <p>It seems to be related to how many other items are also being displayed in the window. If there are no other items then it always succeeds, but when there are many other complex UI elements being displayed alongside it, then the find fails.</p>
  
  <p>It appears as though we're hitting some kind of internal element limit. I can't find any documented element limit mentioned for any of the automation API's - is there some way around this? I'm thinking I might have to write my own implemententation of <code>FindFirst</code> which does the tree walk manually itself... As far as I can tell this should work, because my tree-printer utility function does exactly that, and it's ok, but it seems like this would be unnecessary and slow :-(</p>
  
  <p>Any help would be greatly appreciated</p>