How to Specify Contains in UI Automation PropertyCondition
I am using UI Automation for GUI testing.
The title of my window contains the application name appended with the filename.
So, I want to specify Contains in my PropertyCondition name.
I checked the overload, but it has to do with ignoring the name value value.
Can anyone please advise me how to specify Contains in my PropertyCondition name?
Hello,
kvk938
source to share
As far as I know, this is not a way to do a contains when using the name property, but you can do something like this.
/// <summary>
/// Returns the first automation element that is a child of the element you passed in and contains the string you passed in.
/// </summary>
public AutomationElement GetElementByName(AutomationElement aeElement, string sSearchTerm)
{
AutomationElement aeFirstChild = TreeWalker.RawViewWalker.GetFirstChild(aeElement);
AutomationElement aeSibling = null;
while ((aeSibling = TreeWalker.RawViewWalker.GetNextSibling(aeFirstChild)) != null)
{
if (aeSibling.Current.Name.Contains(sSearchTerm))
{
return aeSibling;
}
}
return aeSibling;
}
Then you will do this to get the desktop and pass the desktop with your string to the above method
/// <summary>
/// Finds the automation element for the desktop.
/// </summary>
/// <returns>Returns the automation element for the desktop.</returns>
public AutomationElement GetDesktop()
{
AutomationElement aeDesktop = AutomationElement.RootElement;
return aeDesktop;
}
Full usage would look something like this:
AutomationElement oAutomationElement = GetElementByName(GetDesktop(), "Part of my apps name");
source to share
I tried Max Young's solution but couldn't wait for it to complete. Maybe my visual tree was too big, not sure. I decided that this is my application and I have to use the knowledge of the specific type of element I am looking for, in my case it was a WPF TextBlock, so I did this:
public AutomationElement FindElementBySubstring(AutomationElement element, ControlType controlType, string searchTerm)
{
AutomationElementCollection textDescendants = element.FindAll(
TreeScope.Descendants,
new PropertyCondition(AutomationElement.ControlTypeProperty, controlType));
foreach (AutomationElement el in textDescendants)
{
if (el.Current.Name.Contains(searchTerm))
return el;
}
return null;
}
example of use:
AutomationElement textElement = FindElementBySubstring(parentElement, ControlType.Text, "whatever");
and it worked quickly.
source to share