public static void CloseModalWindows() { AutomationElement root = AutomationElement.FromHandle(System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle); if (root == null) { return; } if (!root.TryGetCurrentPattern(WindowPattern.Pattern, out object pattern)) { return; } WindowPattern window = (WindowPattern)pattern; if (window.Current.WindowInteractionState != WindowInteractionState.ReadyForUserInteraction) { foreach (AutomationElement element in root.FindAll(TreeScope.Children, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Window))) { if (element.TryGetCurrentPattern(WindowPattern.Pattern, out pattern)) { WindowPattern childWindow = (WindowPattern)pattern; if (childWindow.Current.WindowInteractionState == WindowInteractionState.ReadyForUserInteraction) { childWindow.Close(); } } } } }
private void CloseModalWindows() { // get the main window AutomationElement root = AutomationElement.FromHandle(Process.GetCurrentProcess().MainWindowHandle); if (root == null) { return; } // it should implement the Window pattern if (!root.TryGetCurrentPattern(WindowPattern.Pattern, out object pattern)) { return; } WindowPattern window = (WindowPattern)pattern; if (window.Current.WindowInteractionState != WindowInteractionState.ReadyForUserInteraction) { // get sub windows foreach (AutomationElement element in root.FindAll(TreeScope.Children, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Window))) { // hmmm... is it really a window? if (element.TryGetCurrentPattern(WindowPattern.Pattern, out pattern)) { // if it's ready, try to close it WindowPattern childWindow = (WindowPattern)pattern; if (childWindow.Current.WindowInteractionState == WindowInteractionState.ReadyForUserInteraction) { childWindow.Close(); } } } } }
//---------------------------------------------------------------------- // // Public Methods // //---------------------------------------------------------------------- /// <summary> /// Will close the specified window. /// </summary> /// <param name="window">Window to close.</param> public static void CloseWindow(AutomationElement window) { bool supportedWindowPattern = false; foreach (AutomationPattern pattern in window.GetSupportedPatterns()) { if (pattern == WindowPattern.Pattern) { WindowPattern wndPattern = (WindowPattern)window.GetCurrentPattern(WindowPattern.Pattern); wndPattern.WaitForInputIdle(Timeout); wndPattern.Close(); supportedWindowPattern = true; break; } } if (!supportedWindowPattern) { UnsafeNativeMethods.SendMessage( (IntPtr)window.Current.NativeWindowHandle, Win32Messages.WM_DESTROY, IntPtr.Zero, IntPtr.Zero); } }
/// <summary> /// Паттерн закрытия окна! /// </summary> /// <param name="element"></param> public void CloseWindowPattern(AutomationElement element) { WindowPattern windowPattern = (WindowPattern)element.GetCurrentPattern(WindowPattern.Pattern); AutoItX.Sleep(2000); windowPattern.Close(); }
// Walk up the hierarchy till you find a window that supports the WindowPattern // and call the Close method on the pattern. public static void CloseWindow(AutomationElement leChild) { AutomationElement le = GetWindowPatternElement(leChild); WindowPattern wp = le.GetCurrentPattern(WindowPattern.Pattern) as WindowPattern; Debug.Assert(wp != null, "wp cannot be null here"); wp.Close(); }
public void Close() { STAHelper.Invoke( delegate() { WindowPattern.Close(); } ); }
private void CloseDialog(AutomationElement dialog) { WindowPattern windowPattern = dialog.GetCurrentPattern(WindowPattern.Pattern) as WindowPattern; if (windowPattern != null) { windowPattern.Close(); } }
void System.IDisposable.Dispose() { if (_windowPattern != null) { _windowPattern.Close(); _windowPattern = null; } _element = null; _hwnd = 0; }
/// <summary> /// 关闭 被测试程序. /// </summary> public void CloseApp() { Console.WriteLine("尝试关闭程序:[{0}]", APP_NAME); // 休眠指定时间. Thread.Sleep(DEFAULT_SLEEP_TIME); // 关闭被测试程序 WindowPattern wpCloseForm = (WindowPattern)testMainForm.GetCurrentPattern(WindowPattern.Pattern); wpCloseForm.Close(); }
public void Close(bool log) { if (log) { procedureLogger.Action(string.Format("Close {0}.", this.NameAndType)); } WindowPattern wp = (WindowPattern)element.GetCurrentPattern(WindowPattern.Pattern); wp.Close(); }
public static void CloseWindow(AutomationElement window) { try { WindowPattern wndPattern = window.GetCurrentPattern(WindowPattern.Pattern) as WindowPattern; wndPattern.Close(); } catch (Exception) { throw; } }
// </Snippet101> // <Snippet102> ///-------------------------------------------------------------------- /// <summary> /// Calls the WindowPattern.Close() method for an associated /// automation element. /// </summary> /// <param name="windowPattern"> /// The WindowPattern control pattern obtained from /// an automation element. /// </param> ///-------------------------------------------------------------------- private void CloseWindow(WindowPattern windowPattern) { try { windowPattern.Close(); } catch (InvalidOperationException) { // object is not able to perform the requested action return; } }
/// <summary> /// /// </summary> /// <param name="waitTime"></param> public void Close(double waitTime = 0.1) { try { WindowPattern.Close(); } catch (Exception ex) { throw new Exception("Failed to close the window. " + ex); } Thread.Sleep((int)(waitTime * 1000)); }
void System.IDisposable.Dispose() { if (_windowPattern != null) { _windowPattern.Close(); _windowPattern = null; } if (_process != null) { _process.WaitForExit(); _process = null; } }
public virtual bool Close() { try { if (IsClosed) { return(false); } wp.Close(); return(true); } catch (ElementNotAvailableException) { return(false); } }
private void _CloseMsgBox() { /////MessageBox.Show(sReportName, "Comparing Reports.......Leaving me alone!", MessageBoxButtons.OK, MessageBoxIcon.Warning); // get the main window AutomationElement root = AutomationElement.FromHandle(Process.GetCurrentProcess().MainWindowHandle); if (root == null) { return; } // it should implement the Window pattern object pattern; if (!root.TryGetCurrentPattern(WindowPattern.Pattern, out pattern)) { return; } WindowPattern window = (WindowPattern)pattern; if (window.Current.WindowInteractionState != WindowInteractionState.ReadyForUserInteraction) { // get sub windows foreach (AutomationElement element in root.FindAll(TreeScope.Children, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Window))) { // hmmm... is it really a window? if (element.TryGetCurrentPattern(WindowPattern.Pattern, out pattern)) { // if it's ready, try to close it WindowPattern childWindow = (WindowPattern)pattern; if (childWindow.Current.WindowInteractionState == WindowInteractionState.ReadyForUserInteraction) { childWindow.Close(); } } } } }
public void CleanUp() { try { // Tell the application's main window to close. WindowPattern window = _userApplicationElement.GetCurrentPattern(WindowPattern.Pattern) as WindowPattern; window.Close(); if (!_userAppProcess.WaitForExit(3000)) { // We waited 3 seconds for the User Application to close on its own. // Send a close request again through the process class. _userAppProcess.CloseMainWindow(); } // All done trying to close the window, terminate the process _userAppProcess.Close(); _userAppProcess = null; } catch (Exception ex) { // I know this is bad, but catching the world is better than letting it fail. } }
static void Main(string[] args) { try { Console.WriteLine("\nBegin WPF UIAutomation test run\n"); Console.WriteLine("Launching StatCalc application"); Process p = Process.Start("..\\..\\..\\StatCalc\\bin\\Debug\\StatCalc.exe"); Thread.Sleep(2000); AutomationElement aeDesktop = AutomationElement.RootElement; AutomationElement aeForm = null; int numWaits = 0; do { aeForm = aeDesktop.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.NameProperty, "StatCalc")); Console.WriteLine("Looking for StatCalc . . . "); ++numWaits; Thread.Sleep(100); } while (aeForm == null && numWaits < 50); if (aeForm == null) { throw new Exception("Failed to find StatCalc"); } else { Console.WriteLine("Found it!"); } Console.WriteLine("Finding all user controls"); AutomationElement aeButton = aeForm.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.NameProperty, "Calculate")); AutomationElementCollection aeAllTextBoxes = aeForm.FindAll(TreeScope.Children, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit)); AutomationElement aeTextBox1 = aeAllTextBoxes[1]; // caution: implied index order AutomationElement aeTextBox2 = aeAllTextBoxes[0]; AutomationElement aeRadioButton1 = aeForm.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.NameProperty, "Arithmetic Mean")); AutomationElement aeRadioButton2 = aeForm.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.NameProperty, "Geometric Mean")); AutomationElement aeRadioButton3 = aeForm.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.NameProperty, "Harmonic Mean")); Console.WriteLine("\nSetting input to '30 60'"); ValuePattern vpTextBox1 = (ValuePattern)aeTextBox1.GetCurrentPattern(ValuePattern.Pattern); vpTextBox1.SetValue("30 60"); Console.WriteLine("Selecting 'Geometric Mean' "); SelectionItemPattern ipSelectRadioButton2 = (SelectionItemPattern)aeRadioButton2.GetCurrentPattern(SelectionItemPattern.Pattern); ipSelectRadioButton2.Select(); Console.WriteLine("Clicking on Calculate button"); InvokePattern ipClickButton1 = (InvokePattern)aeButton.GetCurrentPattern(InvokePattern.Pattern); ipClickButton1.Invoke(); Thread.Sleep(1500); Console.WriteLine("\nChecking textBox2 for '42.4264'"); string result = (string)aeTextBox2.GetCurrentPropertyValue(ValuePattern.ValueProperty); if (result == "42.4264") { Console.WriteLine("Found it"); Console.WriteLine("\nTest scenario: Pass"); } else { Console.WriteLine("Did not find it"); Console.WriteLine("\nTest scenario: *FAIL*"); } Console.WriteLine("\nClosing application in 5 seconds"); Thread.Sleep(5000); WindowPattern wpCloseForm = (WindowPattern)aeForm.GetCurrentPattern(WindowPattern.Pattern); wpCloseForm.Close(); Console.WriteLine("\nEnd test run\n"); Console.ReadLine(); } catch (Exception ex) { Console.WriteLine("Fatal error: " + ex.Message); Console.ReadLine(); } } // Main()
/// <summary> /// Closes the window. /// </summary> /// <param name="control">The UI Automation element.</param> internal static void CloseWindow(AutomationElement control) { WindowPattern pattern = (WindowPattern)CommonUIAPatternHelpers.CheckPatternSupport(WindowPattern.Pattern, control); pattern.Close(); }
static void Main(string[] args) { try { List <string> perems = new List <string>(); // Загружаем значения теста XmlDocument xDoc = new XmlDocument(); xDoc.Load("input.xml"); XmlElement xRoot = xDoc.DocumentElement; foreach (XmlNode xnode in xRoot) { // обходим все дочерние узлы элемента user foreach (XmlNode childnode in xnode.ChildNodes) { // если узел - company if (childnode.Name == "perem1") { perems.Add(childnode.InnerText); } // если узел age if (childnode.Name == "perem2") { perems.Add(childnode.InnerText); } } } //запускаем процесс нашего приложения Process p = Process.Start("..\\..\\..\\StatCalc\\bin\\Debug\\StatCalc.exe"); Thread.Sleep(2000); // на всякий случай ставим задержку AutomationElement aeDesktop = AutomationElement.RootElement; AutomationElement aeForm = null; int numWaits = 0; do { aeForm = aeDesktop.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.NameProperty, "StatCalc")); ++numWaits; Thread.Sleep(100); }while (aeForm == null && numWaits < 50); if (aeForm == null) { throw new Exception("Окно не было получено"); } //////////////////////////////////////////////////////////Получаем все элементы AutomationElement aeButton = aeForm.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.NameProperty, "Расчитать")); AutomationElementCollection aeAllTextBoxes = aeForm.FindAll(TreeScope.Children, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit)); // получаем textbox AutomationElement aeTextBox1 = aeAllTextBoxes[1]; // закидываем textbox в массив AutomationElement aeTextBox2 = aeAllTextBoxes[0]; AutomationElement aeRadioButton1 = aeForm.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.NameProperty, "Сумма")); AutomationElement aeRadioButton2 = aeForm.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.NameProperty, "Произведение")); ValuePattern vpTextBox1 = (ValuePattern)aeTextBox1.GetCurrentPattern(ValuePattern.Pattern); vpTextBox1.SetValue(perems[0] + " " + perems[1]); Thread.Sleep(1000); //Получаем круглые кнопки SelectionItemPattern ipSelectRadioButton2 = (SelectionItemPattern)aeRadioButton2.GetCurrentPattern(SelectionItemPattern.Pattern); SelectionItemPattern ipSelectRadioButton1 = (SelectionItemPattern)aeRadioButton1.GetCurrentPattern(SelectionItemPattern.Pattern); ipSelectRadioButton2.Select(); Thread.Sleep(1000); InvokePattern ipClickButton1 = (InvokePattern)aeButton.GetCurrentPattern(InvokePattern.Pattern); ipClickButton1.Invoke(); Thread.Sleep(1500); string[] result = new string[3]; result[0] = (string)aeTextBox2.GetCurrentPropertyValue(ValuePattern.ValueProperty); //Тест номер 1 if (result[0] == "1800,0000") { Console.WriteLine("\nТест1 прошёл успешно"); } else { Console.WriteLine("\nТест1 провален"); } //Тест номер 2 vpTextBox1.SetValue(perems[2] + " " + perems[3]); Thread.Sleep(1000); ipSelectRadioButton1.Select(); Thread.Sleep(1000); ipClickButton1.Invoke(); Thread.Sleep(1000); result[1] = (string)aeTextBox2.GetCurrentPropertyValue(ValuePattern.ValueProperty); if (result[1] == "-182,0000") { Console.WriteLine("\nТест2 прошёл успешно"); } else { Console.WriteLine("\nТест2 провален"); } // Тест номер 3 vpTextBox1.SetValue(perems[4] + " " + perems[5]); Thread.Sleep(1000); ipSelectRadioButton1.Select(); Thread.Sleep(1000); ipClickButton1.Invoke(); Thread.Sleep(1000); result[2] = (string)aeTextBox2.GetCurrentPropertyValue(ValuePattern.ValueProperty); if (result[2] == "-10001,0000") { Console.WriteLine("\nТест3 прошёл успешно"); } else { Console.WriteLine("\nТест3 провален"); } Console.WriteLine("\nПриложение закроется через 5 секунд"); Thread.Sleep(5000); // получаем элемент закрытия формы WindowPattern wpCloseForm = (WindowPattern)aeForm.GetCurrentPattern(WindowPattern.Pattern); wpCloseForm.Close(); Console.WriteLine("\nТесты закончены!\nРезультаты можно увидеть в xml документе: 'output.xml'"); //Записываем результаты теста XmlDocument xDocOutput = new XmlDocument(); xDocOutput.Load("output.xml"); XmlElement xRoot2 = xDocOutput.DocumentElement; int i = 0; foreach (XmlNode xnode in xRoot2) { foreach (XmlNode childnode in xnode.ChildNodes) { if (childnode.Name == "results") { XmlText nameText = xDocOutput.CreateTextNode(result[i]); childnode.AppendChild(nameText); i++; } } } xDocOutput.Save("output.xml"); Console.ReadKey(); } catch (Exception ex) { Console.WriteLine("При запуске тестовой программы, произошла ошибка!: " + ex.Message); Console.ReadLine(); } }
static void Main(string[] args) { try { Console.WriteLine("\nBegin WinForm UIAutomation test run\n"); // launch Form1 application // get refernce to main Form control // get references to user controls // manipulate application // check resulting state and determine pass/fail Console.WriteLine("\nBegin WinForm UIAutomation test run\n"); Console.WriteLine("Launching WinFormTest application"); //启动被测试的程序 Process p = Process.Start(@"E:\Project\WinFormTest\WinFormTest\bin\Debug\WinFormTest.exe"); //自动化根元素 AutomationElement aeDeskTop = AutomationElement.RootElement; Thread.Sleep(2000); AutomationElement aeForm = AutomationElement.FromHandle(p.MainWindowHandle); //获得对主窗体对象的引用,该对象实际上就是 Form1 应用程序(方法一) //if (null == aeForm) //{ // Console.WriteLine("Can not find the WinFormTest from."); //} //获得对主窗体对象的引用,该对象实际上就是 Form1 应用程序(方法二) int numWaits = 0; do { Console.WriteLine("Looking for WinFormTest……"); //查找第一个自动化元素 aeForm = aeDeskTop.FindFirst(TreeScope.Children, new PropertyCondition( AutomationElement.NameProperty, "Form1")); ++numWaits; Thread.Sleep(100); } while (null == aeForm && numWaits < 50); if (null == aeForm) { throw new NullReferenceException("Failed to find WinFormTest."); } else { Console.WriteLine("Found it!"); } Console.WriteLine("Finding all user controls"); //找到第一次出现的Button控件 AutomationElement aeButton = aeForm.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.NameProperty, "button1")); //找到所有的TextBox控件 AutomationElementCollection aeAllTextBoxes = aeForm.FindAll(TreeScope.Children, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit)); // 控件初始化的顺序是先初始化后添加到控件 // this.Controls.Add(this.textBox3); // this.Controls.Add(this.textBox2); // this.Controls.Add(this.textBox1); AutomationElement aeTextBox1 = aeAllTextBoxes[2]; AutomationElement aeTextBox2 = aeAllTextBoxes[1]; AutomationElement aeTextBox3 = aeAllTextBoxes[0]; Console.WriteLine("Settiing input to '30'"); //通过ValuePattern设置TextBox1的值 ValuePattern vpTextBox1 = (ValuePattern)aeTextBox1.GetCurrentPattern(ValuePattern.Pattern); vpTextBox1.SetValue("30"); Console.WriteLine("Settiing input to '50'"); //通过ValuePattern设置TextBox2的值 ValuePattern vpTextBox2 = (ValuePattern)aeTextBox2.GetCurrentPattern(ValuePattern.Pattern); vpTextBox2.SetValue("50"); Thread.Sleep(1500); Console.WriteLine("Clickinig on button1 Button."); //通过InvokePattern模拟点击按钮 InvokePattern ipClickButton1 = (InvokePattern)aeButton.GetCurrentPattern(InvokePattern.Pattern); ipClickButton1.Invoke(); Thread.Sleep(1500); //验证计算的结果与预期的结果是否相符合 Console.WriteLine("Checking textBox3 for '80'"); TextPattern tpTextBox3 = (TextPattern)aeTextBox3.GetCurrentPattern(TextPattern.Pattern); string result = tpTextBox3.DocumentRange.GetText(-1);//获取textbox3中的值 //获取textbox3中的值 //string result = (string)aeTextBox2.GetCurrentPropertyValue(ValuePattern.ValueProperty); if ("80" == result) { Console.WriteLine("Found it."); Console.WriteLine("TTest scenario: *PASS*"); } else { Console.WriteLine("Did not find it."); Console.WriteLine("Test scenario: *FAIL*"); } Console.WriteLine("Close application in 5 seconds."); Thread.Sleep(5000); //实现关闭被测试程序 WindowPattern wpCloseForm = (WindowPattern)aeForm.GetCurrentPattern(WindowPattern.Pattern); wpCloseForm.Close(); Console.WriteLine("\nEnd test run\n"); } catch (Exception ex) { Console.WriteLine("Fatal error: " + ex.Message); } }
static void Main(string[] args) { try { Console.WriteLine("\nBegin WinForm UIAutomayion test run\n"); Console.WriteLine("Launching WinFormTest application"); //启动被测程序 string appPath = "c:\\users\\geek\\documents\\visual studio 2013\\Projects\\WpfApplication1\\WpfApplication1\\bin\\Debug\\WpfApplication1.exe"; Process process = Process.Start(@appPath); //获取被测程序的主窗口 AutomationElement appForm = FindWindowByProcessId(process.Id); //下拉菜单获取 AutomationElement combox = FindElementById(appForm, "comboBox1"); ExpandCollapsePattern currentpattern = GetExpandCollapsePattern(combox); currentpattern.Expand(); Thread.Sleep(1000); currentpattern.Collapse(); //点击按钮 AutomationElement btn = FindElementById(appForm, "button1"); InvokePattern ipBtn = GetInvokePattern(btn); ipBtn.Invoke(); Thread.Sleep(1000); //文本框操作 AutomationElement textBox = FindElementById(appForm, "textBox1"); ValuePattern vpTextBox = GetValuePattern(textBox); vpTextBox.SetValue("Kimi @163.com"); //选择按钮的操作 SelectionItemPattern sip = GetSelectionItemPattern(FindElementById(appForm, "radioButton1")); sip.Select(); Thread.Sleep(1000); sip.Select(); TogglePattern tp = GetTogglePattern(FindElementById(appForm, "checkBox1")); bool isCheck = tp.Current.ToggleState == ToggleState.On;//三种状态 On Off Indeterminate if (!isCheck) { tp.Toggle(); } Thread.Sleep(1000); tp.Toggle(); //下拉列表操作 AutomationElement list = FindElementById(appForm, "listView1"); AutomationElementCollection rows = FindElementCollectionByControlType(list, ControlType.ListItem); MutlSelect(new int[] { 1 }, rows, false); Thread.Sleep(3000); //对窗口大小/关闭的操作 WindowPattern wp = GetWindowPattern(appForm); //wp.SetWindowVisualState(WindowVisualState.Maximized); //最大化 //Thread.Sleep(1000); //wp.SetWindowVisualState(WindowVisualState.Minimized); //最小化 //Thread.Sleep(1000); //wp.SetWindowVisualState(WindowVisualState.Normal); //正常值 //Thread.Sleep(1000); wp.Close(); //关闭窗口 } catch (Exception ex) { Console.WriteLine("Fatal error:" + ex.Message); } }
internal static void CloseWindow(AutomationElement windowElement) { WindowPattern window = (WindowPattern)windowElement.GetCurrentPattern(WindowPattern.Pattern); window.Close(); }