Automation of User Interface in WPF






All basic control in WPF has a corresponding AutomationPeer class that implements all the basic functionality a user can do with that control. These classes are named ButtonAutomationPeer and so on. If a user can scroll it then so can you programmatically. All controls implementing AutomationPeer has a few methods in common and for us in this example GetPattern is the most useful one. By calling that function you can request a pattern for an action provider.

The steps you go through to automate something in the user interface are the following:

  1. Create an automation peer object from a UI Control
  2. Create an action provider
  3. Request an automation pattern from the automation peer object. With PatternInterface you can specify what kind of automation pattern you’re requestion. If it doesn’t exist null will be returned.
  4. Use the action provider to make the automation

The following namespaces are being used in these examples below:

using System.Windows.Automation;
using System.Windows.Automation.Peers;
using System.Windows.Automation.Provider;

Example 1 – scroll a ListBox

// Step 1
ListBoxAutomationPeer listBoxAutomationPeer = new ListBoxAutomationPeer(myWindow.ListBox1);

// Step 2-3
IScrollProvider scrollProvider;
scrollProvider = (IScrollProvider)listBoxAutomationPeer.GetPattern(PatternInterface.Scroll);

// Step 4 (horizontal and vertical scroll)
scrollProvider.Scroll(ScrollAmount.NoAmount, ScrollAmount.LargeIncrement);

Example 2 – select item in a ListBox

// Step 1 (we also need an automation peer from the listbox itself)
ListBoxAutomationPeer listBoxAutomationPeer = new ListBoxAutomationPeer(myWindow.ListBox1);
ListBoxItemAutomationPeer listBoxItemAutomationPeer = new ListBoxItemAutomationPeer(myWindow.ListBox1.Items[14], listBoxAutomationPeer);

// Step 2-3
ISelectionItemProvider selectionItemProvider;
selectionItemProvider = (ISelectionItemProvider)listBoxItemAutomationPeer.GetPattern(PatternInterface.SelectionItem);

// Step 4 (select 
selectionItemProvider.Select();

Example 3 – click a button

// Step 1
ButtonAutomationPeer buttonAutomationPeer = new ButtonAutomationPeer(myWindow.Button1);

// Step 2-3
IInvokeProvider invokeProvider;
invokeProvider = (IInvokeProvider)buttonAutomationPeer.GetPattern(PatternInterface.Invoke);

// Step 4
invokeProvider.Invoke();