Skip to content
Tom Austin edited this page Jul 11, 2020 · 2 revisions

Finding an Element

Find

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.

Basic Usage

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.

Conditions

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

Basic Expression
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 Expression
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)));
} 
Or Expression
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 By Parent

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);
} 

Caching

Find can find elements extremely quickly when combined with caching. Please refer to that wiki article for more information.