UI Automation Fraamewark using WPF

23171 ワード

記事の由来: http://www.codeproject.com/Articles/34038/UI-Automation-Framework-using-WPF
Introduction
This artic le shows how to make use of UI Automation Framward using WPF to develop an UI Automasted appration.The UI Automation Library is included in the.NET Frame ew 3.0/3.5.The concept seem to straigward.Every UI contratory 45 tory  AutomationElementis defined as the「AutomationElement」、which is the desktop.
Another way to get the  AutomationElement Object to a given Window is by starting a「RootElement」、and then using the  AutomationElement to get the  Processobject.
Background
I am shring information on this frame ewark because I found it very interesting and had a very hard time developing a full feature appination.On the internet、I found a very smaall amount or I must say noadequator.com.I am not going to explayin what is UI Automation Framwark and its details.You can find a theortical articale on internet/MSDN.Here I will provide how to make use of the UI Automatomation libries,and how to Playwith frame Formon.
I was gives the scenaro,where there is already apaplication developed in WinForms using.NET Fraameeeewaork 2.0.And UI Automation aplication isdeveloped in WPFusing.NET Fraamebook 3.5.The sample apple apariation UI aphphphininininininininininininatototototototototototototototototototototototototomomomomomomomomomomomomomomomomomomomomomomomomomomotion UI UI UI UI UI UI aaaaatotototototototototototototoClass Libries、how to find controls and write auted test cases.
The solution contains 2 project s,one project is WinForms appection tageting.NET Frame 2.0 and the second project is WPF appings.NET Frame 3.5.The WPF appliation is baically term  Process MainWindowHandle 、  AutomationElement 、  Textbox、  dropdown、etc.I showd singlecheckboxexecution on a single button click、but once you get the idea、you can Playwith it and write a series of test caseass can be exuted in a single action.
Note:When you comple this solution、I set output path for WinForm appication to bin folder of WPF appration just to make it easure to undent and load the application.
Using the Code
How to Load Apple and find Root Instance of target aplication
Automation.RootElement: It represents the desktop,and all other appronication s on desktop apparas child windows of this  grid.The below code shows how to find the target instance of the appration from the desktop.

 Collappse
 |  Copyコード
private void LoadApplication_Click(object sender, RoutedEventArgs e)
{
  //Start the client application
  this._clientProcess = Process.Start
	(this._targetApplicationPath + @"\" + this._targetApplicationName);

  Thread.Sleep(100);

  int count = 0;

  do
  {
    ++count;
    //Get the Root Element of client application from the Desktop tree
    this._clientAppRootInstance = 
	AutomationElement.RootElement.FindFirst(TreeScope.Children,
        	new PropertyCondition(AutomationElement.NameProperty, "SampleForm"));

    Thread.Sleep(100);
  }
  while (this._clientAppRootInstance == null && count < 10);

  if (this._clientAppRootInstance == null)
  {
     MessageBox.Show("SampleForm application instance not found. 
			Close application and try again!!!");
     return;
  }
}
How to find Textbox and use of TextPatternTestCase :This oject exposes compone properties of the UI elemens they represent.One of these properties is the control type,which defines its baic apearance and functions as a single cognizable ent.elemens expose control patterns that provide properties specific to their control types.Control patterns also expose methat enable to get further information about the element and to viprovident put.459167RootElement:It represents enumeration which has values to specify the scope of element within the UI Automation tree or in Root elementAutomationElement:It represents the condition that tests whether property has a specifed valueTreeScope:It represents the commbination of 2 or more conditions that must all be  PropertyConditionfor a particular match
 Collappse
 |  Copyコード
private void TextBoxTest_Click(object sender, RoutedEventArgs e)
{
   if (this._clientAppRootInstance != null)
   {
     //Get the textbox (appears as Document Control Type) instance from 
     //application root instance as it will child
     //and add the AndCondition so minimize the search time in tree
     textBoxInstance = this._clientAppRootInstance.FindFirst(TreeScope.Children,
                           new AndCondition(
                           new PropertyCondition
			(AutomationElement.AutomationIdProperty, "txtDocument"),
                           new PropertyCondition
			(AutomationElement.ControlTypeProperty, ControlType.Document)
                            ));
     if (textBoxInstance == null)
     {
       MessageBox.Show("Textbox instance not found");
     }
     else
     {
       //Set focus to textbox
       textBoxInstance.SetFocus();
       //Use SendKeys to send text
       System.Windows.Forms.SendKeys.SendWait(_tempText);
     }
   }
} 
UI Automation supports different types of patterns depending uon the controls.Below is the code sample ofAndCondition.

 Collappse
 |  Copyコード
private void CompareText_Click(object sender, RoutedEventArgs e)
{
  //Control that accept the values as represented as TextPattern
  TextPattern textboxPattern = 
	(TextPattern)textBoxInstance.GetCurrentPattern(TextPattern.Pattern);
  if (textboxPattern == null)
  {
    MessageBox.Show("Textbox instance not found.");
  }
  else
  {
    string enteredText = textboxPattern.DocumentRange.GetText(-1).Trim();
    if (string.Equals(enteredText, _tempText, 
	StringComparison.InvariantCultureIgnoreCase))
    {
      MessageBox.Show("Compare test passed");
    }
    else
    {
      MessageBox.Show("Compare test failed.");
    }
   }
}
How to select value from dropdown and use of Expand CollappsePattern and Selection ItemPattern
Below is the code sample that shows how to select value from  true   TextPatternsupportscomboboxand  Combobox   ExpandCollapsePattern contains  SelectionItemPatternasチルドレンand  Combobox contains the collection of  List in  List
 Collappse
 |  Copyコード
private void ComboBoxTest_Click(object sender, RoutedEventArgs e)
{
   if (this._clientAppRootInstance != null)
   {
     //Get the combo box instance from application root instance as its 
     //child instance and find by its name
     AutomationElement comboboxInstance = 
	this._clientAppRootInstance.FindFirst(TreeScope.Children,
         new PropertyCondition(AutomationElement.AutomationIdProperty, "cmbMonth"));
     if (comboboxInstance == null)
     {
        MessageBox.Show("ComboBox instance not found.");
     }
     else
     {
         //Get the List child control inside the combo box
        AutomationElement comboboxList = comboboxInstance.FindFirst(TreeScope.Children,
              new PropertyCondition
		(AutomationElement.ControlTypeProperty, ControlType.List));

         //Get the all the listitems in List control
         AutomationElementCollection comboboxItem = 
			comboboxList.FindAll(TreeScope.Children,
             new PropertyCondition(AutomationElement.ControlTypeProperty, 
						ControlType.ListItem));

         //Combo Box support 2 patterns, ExpandCollapsePatterna and SelectionItemPattern
         //Expand the combobox
         ExpandCollapsePattern expandPattern = 
		(ExpandCollapsePattern)comboboxInstance.GetCurrentPattern
		(ExpandCollapsePattern.Pattern);

         expandPattern.Expand();

           //Index to set in combo box
           AutomationElement itemToSelect = comboboxItem[comboboxItem.Count - 7];

           //Finding the pattern which need to select
          Object selectPattern = null;
          if (itemToSelect.TryGetCurrentPattern
		(SelectionItemPattern.Pattern, out selectPattern))
          {
             ((SelectionItemPattern)selectPattern).Select();
          }
       }
   }
}
How to find button and use of InvokePatternListItems supports  combobox、which represents the control that initiates or performs a single action.Like code executes on button click,it does not mantain the state when activated.

 Collappse
 |  Copyコード
private void AddDataRowTest_Click(object sender, RoutedEventArgs e)
{
   if (this._clientAppRootInstance != null)
   {
      //Get the Add Button instance from root instance, finding it by name 
      //and its child in root instance
      AutomationElement buttonAddInstance = 
	this._clientAppRootInstance.FindFirst(TreeScope.Children,
        	new PropertyCondition(AutomationElement.AutomationIdProperty, "btnAdd"));
      if (buttonAddInstance == null)
      {
         MessageBox.Show("Add button instance not found");
      }
      else
      {
         //Button support Invoke Pattern
         InvokePattern buttonPattern = 
	    (InvokePattern)buttonAddInstance.GetCurrentPattern(InvokePattern.Pattern);
         //Once get the pattern then calling Invoke method on that
         buttonPattern.Invoke();
      }
   }
}
How to atch Event Handler on control in taget appration
The code sample below shows how to create and atach an イベントハンドルオン  Button in the target appration:

 Collappse
 |  Copyコード
private void CheckBoxTest_Click(object sender, RoutedEventArgs e)
{
   if (this._clientAppRootInstance != null)
   {
      //Get the checkbox instance from root application instance and 
      //it appears as child in the tree and finding by its name
      AutomationElement checkBoxInstance = 
	this._clientAppRootInstance.FindFirst(TreeScope.Children,
         new PropertyCondition(AutomationElement.AutomationIdProperty, "chkCheckBox"));
      
         if (checkBoxInstance == null)
         {
            MessageBox.Show("Checkbox instance not found");
         }
         else
         {
            //Create EventHandler for CheckBox
            AutomationPropertyChangedEventHandler checkBoxEvent = 
	    new AutomationPropertyChangedEventHandler(CheckBoxIsChecked_EventHandler);

            //Attaching the EventHandler
            Automation.AddAutomationPropertyChangedEventHandler(_clientAppRootInstance, 
		TreeScope.Children, checkBoxEvent, AutomationElement.NameProperty);
         }
    }
}
Below is the Event Handler code which executes when user checks the checkbox on target aplication:

 Collappse
 |  Copyコード
private void CheckBoxIsChecked_EventHandler(object sender, AutomationEventArgs e)
{
    //If CheckBox is checked on target application then this get executed
    AutomationElement ar = sender as AutomationElement;

    MessgeBox.Show("Checkbox IsChecked event executed.");
}
I hope this post is useful to others.Please rate this artic and provide your valuable feedback.