public Form1() { InitializeComponent(); this.textBox1.AccessibilityObject.Name = "t1"; this.textBox3.AccessibilityObject.Name = "t3"; } private void button1_Click(object sender, EventArgs e) { var t = this.textBox1; int i = int.Parse(textBox1.Text); int j = int.Parse(textBox2.Text); textBox3.Text = (i + j).ToString(); } private void testBtn_Name_Click(object sender, EventArgs e) { textBox3.Text = "test"; }
上面是被自動化的代碼。測試
1 /// <summary> 2 /// 應用程序的主入口點。 3 /// </summary> 4 [STAThread] 5 static void Main() 6 { 7 //啓動被測試的程序 8 Process p = Process.Start(@"C:\vs2015項目\Automation\Automation\bin\Debug\Automation.exe"); 9 10 //自動化根元素,能夠認爲是桌面. 11 AutomationElement aeDeskTop = AutomationElement.RootElement; 12 13 Thread.Sleep(2000); 14 AutomationElement aeForm = AutomationElement.FromHandle(p.MainWindowHandle); 15 16 #region 獲取 button 並模擬點擊事件。 17 18 //找到窗體。 19 var testForm = aeDeskTop.FindFirst(TreeScope.Children, new PropertyCondition( 20 AutomationElement.NameProperty, "Form1")); 21 22 //經過條件找到窗體裏面的 btn。這個位置 name 屬性對應控件的 Text 屬性。 23 var btnCondition = new AndCondition( 24 new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Button), 25 new PropertyCondition(AutomationElement.NameProperty, "testBtn")); 26 27 var singalCondition = new PropertyCondition(AutomationElement.NameProperty, "testBtn"); 28 29 var testBtn = testForm.FindFirst(TreeScope.Children, btnCondition); // 在桌面的子控件中查找第一個符合條件的窗體。 30 31 //經過InvokePattern模擬點擊按鈕 32 InvokePattern ipClickTestBtn = (InvokePattern)testBtn.GetCurrentPattern(InvokePattern.Pattern); 33 ipClickTestBtn.Invoke(); 34 35 #endregion 36 37 #region 獲取 textbox 並賦值 38 39 var txtCondition1 = new AndCondition( 40 new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit), 41 new PropertyCondition(AutomationElement.NameProperty, "t1")); 42 43 var txtCondition3 = new AndCondition( 44 new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit), 45 new PropertyCondition(AutomationElement.NameProperty, "t3")); 46 47 //設置值 48 var testText1 = testForm.FindFirst(TreeScope.Children, txtCondition1); 49 ValuePattern t1 = (ValuePattern)testText1.GetCurrentPattern(ValuePattern.Pattern); 50 t1.SetValue("30"); 51 52 //獲取值 53 var testText3 = testForm.FindFirst(TreeScope.Children, txtCondition3); 54 var t3 = (TextPattern)testText3.GetCurrentPattern(TextPattern.Pattern); 55 string result2 = t3.DocumentRange.GetText(-1); 56 57 #endregion 58 59 #region 實現關閉被測試程序 60 61 //實現關閉被測試程序 62 WindowPattern wpCloseForm = (WindowPattern)aeForm.GetCurrentPattern(WindowPattern.Pattern); 63 64 #endregion 65 }
上面是控制代碼this