Search code examples
c#windowsui-automationmicrosoft-ui-automation

Find a windows control using partial NameProperty in windows automation


I'm trying to identify a windows static text control using a partial NameProperty. Here's the code I have:

// Get a reference to the window
AutomationElement epoWindow = AutomationElement.RootElement.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.ClassNameProperty, "MsiDialog"));
// Get a reference to the control
AutomationElement epoControl = epoWindow.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.NameProperty, controlText));

I currently need the full controlText string for this to work but I'd like to search for a part of that string and return any controls found. How do I do this? Thanks, John


Solution

  • You can iterate on a child collection with the prefefined TrueCondition, like this:

      foreach(AutomationElement child in epoWindow.FindAll(TreeScope.Subtree, Condition.TrueCondition))
      {
          if (child.Current.Name.Contains("whatever"))
          {
              // do something
          }
      }
    

    PS: You want to carefully choose the TreeScope if you don't want to kill the performance of your app (if it has a big children hierarchy) or wait indefinitely...