-
Notifications
You must be signed in to change notification settings - Fork 2
Finding an Element
The main way to find a UI element with SHAutomation is by using the Find
method. Find will traverse the visual tree and return the first element that matches the passed in conditions. The main strength of Find
is that if you use it along with caching it is incredibly quick and reliable.
Once you have launched or attached to the application you with to interact with you can call Find
off the Window
object. The most basic way to call Find
is by passing the automation id of the element you wish to find.
using var application = Application.Launch("C:\\ApplicationPath\\Application.exe");
using var automation = new UIA3Automation();
{
var window = application.GetMainWindow(automation);
var element = window.Find("elementAutomationId");
}
If an element is found matching the specified automation id it will be returned, if not a ElementNotFoundException
is thrown.
Find
supports conditions as a way of finding UI elements. Conditions are much more flexible than just using an automation id as it allows you to find using properties such as ClassName
, ControlType
or even BoundingRectangle
. Conditions also support And
and Or
expressions which allow sub filtering if more than one element could be found
using var application = Application.Launch("C:\\ApplicationPath\\Application.exe");
using var automation = new UIA3Automation();
{
var window = application.GetMainWindow(automation);
var button = window.Find(x => x.ByControlType(ControlType.Button));
}
using var application = Application.Launch("C:\\ApplicationPath\\Application.exe");
using var automation = new UIA3Automation();
{
var window = application.GetMainWindow(automation);
var button = window.Find(x => x.ByControlType(ControlType.Button).And(x.ByOnScreen(true)));
}
using var application = Application.Launch("C:\\ApplicationPath\\Application.exe");
using var automation = new UIA3Automation();
{
var window = application.GetMainWindow(automation);
var button = window.Find(x => x.ByControlType(ControlType.Button).Or(x.ByControlType(ControlType.ComboBox)));
}
Find supports passing of a parent automation element, in this scenario Find
will only search within the children of the parent element.
using var application = Application.Launch("C:\\ApplicationPath\\Application.exe");
using var automation = new UIA3Automation();
{
var window = application.GetMainWindow(automation);
var parentElement = window.Find("parentId");
var element = window.Find("elementAutomationId", parent: parentElement);
}
Find can find elements extremely quickly when combined with caching. Please refer to that wiki article for more information.