ui automatization example

The .net framework allows to access and automate windows application through the automation api (since .net 3.0).
After the jump I'll show a small example on how to automate a WinForms application.

This small c# code snippet looks for the windows calculator and simulates a click on the "8" button:

using System.Windows.Automation;

string formname = "Calculator";
string buttonname = "8";

AutomationElement aeDesktop = AutomationElement.RootElement;
// start looking for the form from the top
AutomationElement aeForm = aeDesktop.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.NameProperty, formname));
// start looking for the button within the found form
AutomationElement aeButtonExtras = aeForm.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.NameProperty, buttonname));
// calling the button with the automation invoke command
InvokePattern ipButton = (InvokePattern)aeButton.GetCurrentPattern(InvokePattern.Pattern);
ipButton.Invoke();

A useful application that helps finding window elements, automation attributes and control patterns is UISpy.

By @Gerald in
Tags : #.net, #programming, #c#,