/// <summary> /// Capture the window region of the specified size /// </summary> public Microsoft.Test.RenderingVerification.ImageAdapter CaptureWindow(double targetWidth, double targetHeight) { //Reposition Mouse to the origin Input.Input.MoveTo(new System.Windows.Point(0, 0)); //Get window, move it to the origin AutomationElement windowElement = AutomationElement.FromHandle(hWndHost); WindowPattern window = windowElement.GetCurrentPattern(WindowPattern.Pattern) as WindowPattern; window.SetWindowVisualState(WindowVisualState.Normal); TransformPattern transform = windowElement.GetCurrentPattern(TransformPattern.Pattern) as TransformPattern; transform.Move(0, 0); //we need to size the window (IE) to get the client area the correct size //Get the size of the target window AutomationElement clientElement = windowElement.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.ClassNameProperty, "RootBrowserWindow")); Rect clientRect = (Rect)clientElement.GetCurrentPropertyValue(AutomationElement.BoundingRectangleProperty); //Determine what the new size of the window should be to get the client area the correct size System.Windows.Rect ierect = (System.Windows.Rect)windowElement.GetCurrentPropertyValue(AutomationElement.BoundingRectangleProperty); double w = (double)(ierect.Width + targetWidth - clientRect.Width); double h = (double)(ierect.Height + targetHeight - clientRect.Height); transform.Resize(w, h); // Wait for document to load and resize to occurs (assuming render would have occured) Thread.Sleep(3000); //Get bounds of content region, convert to Rectangle form, and capture to image adapter Rect ContentRect = (Rect)clientElement.GetCurrentPropertyValue(AutomationElement.BoundingRectangleProperty); System.Drawing.Rectangle captureRect = new Rectangle((int)ContentRect.X, (int)ContentRect.Y, (int)ContentRect.Width, (int)ContentRect.Height); return(new Microsoft.Test.RenderingVerification.ImageAdapter(captureRect)); }
public void ListSupportedPatterns() { AutomationElement automationElement = GetCurrentAutoElement(); if (automationElement == null) { return; } object objPattern; WindowPattern windowPattern = null; if (true == automationElement.TryGetCurrentPattern(WindowPattern.Pattern, out objPattern)) { windowPattern = objPattern as WindowPattern; } logger.Info(this.Attributes.Name + " support windowPattern: " + (windowPattern != null).ToString()); TransformPattern transformPattern = null; if (true == automationElement.TryGetCurrentPattern(TransformPattern.Pattern, out objPattern)) { transformPattern = objPattern as TransformPattern; } logger.Info(this.Attributes.Name + " support TransformPattern: " + (transformPattern != null).ToString()); InvokePattern invokePattern = null; if (true == automationElement.TryGetCurrentPattern(InvokePattern.Pattern, out objPattern)) { invokePattern = objPattern as InvokePattern; } logger.Info(this.Attributes.Name + " support InvokePattern: " + (invokePattern != null).ToString()); }
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); } }
static void Main() { Application.ThreadExit += new EventHandler(ThreadOnExit); string ApplicationMutex = "BcFFcd23-3456-6543-Fc44abcd1234"; string ApplicationNameText = "[MyApplicationName]"; mutex = new Mutex(true, ApplicationMutex); bool SingleInstance = mutex.WaitOne(0, false); if (!SingleInstance) { MessageBox.Show("Application already running"); string AppProductName = Process.GetCurrentProcess().MainModule.FileVersionInfo.ProductName; Process[] WindowedProcesses = Process.GetProcesses() .Where(p => p.MainWindowHandle != IntPtr.Zero).ToArray(); foreach (Process process in WindowedProcesses.Where(p => p.MainModule.FileVersionInfo.ProductName == AppProductName)) { if (process.Id != Process.GetCurrentProcess().Id) { AutomationElement element = AutomationElement.FromHandle(process.MainWindowHandle); if (!element.Current.IsOffscreen) { WindowPattern WPattern = element.GetCurrentPattern(WindowPattern.Pattern) as WindowPattern; WindowInteractionState state = WPattern.Current.WindowInteractionState; WPattern.SetWindowVisualState(WindowVisualState.Normal); break; } } } } if (SingleInstance) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Automation.AddAutomationEventHandler(WindowPattern.WindowOpenedEvent, AutomationElement.RootElement, TreeScope.Subtree, (UIElm, evt) => { AutomationElement element = UIElm as AutomationElement; if (element != null) { Console.WriteLine(element.Current.Name); Form form = Application.OpenForms.Cast <Form>() .Where(f => f.Text == ApplicationNameText) .FirstOrDefault(); if (form != null) { form.Visible = true; form.WindowState = FormWindowState.Normal; form.Show(); } } }); Application.Run(new MyAppMainForm()); } else { Application.ExitThread(); } }
public static void getScreenshotForWindowwithTitle(string partorfulltext, string screenshotlocation) { AutomationElement root = AutomationElement.RootElement; Condition cndwindows = new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Window); AutomationElementCollection ActiveWindows = root.FindAll(TreeScope.Descendants, cndwindows); AutomationElement ActiveWindow = null; foreach (AutomationElement windw in ActiveWindows) { if (windw.Current.Name.Contains(partorfulltext)) { ActiveWindow = windw; break; } } if (ActiveWindow != null) { ActiveWindow.SetFocus(); WindowPattern wndptn = (WindowPattern)ActiveWindow.GetCurrentPattern(WindowPattern.Pattern); wndptn.SetWindowVisualState(WindowVisualState.Maximized); System.Threading.Thread.Sleep(2000); Bitmap bitmap = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height); Graphics graphics = Graphics.FromImage(bitmap as Image); graphics.CopyFromScreen(0, 0, 0, 0, bitmap.Size); bitmap.Save(Path.Combine(screenshotlocation, Guid.NewGuid() + ".jpg"), ImageFormat.Jpeg); } else { Console.WriteLine("No Window with given Title {0} was found ", partorfulltext); string spz = string.Format("No Window with given Title {0} was found ", partorfulltext); } }
public static void SetWindowVisualState(AutomationElement window, WindowVisualState TargetState) { WindowPattern pattern = window.GetCurrentPattern(WindowPattern.Pattern) as WindowPattern; //pattern.SetWindowVisualState(WindowVisualState.Normal); pattern.SetWindowVisualState(TargetState); }
public void num1() { try { Condition condition = new PropertyCondition(AutomationElement.NameProperty, "Calculator"); AutomationElement appElement = rootElement.FindFirst(TreeScope.Children, condition); WindowPattern window = appElement.GetCurrentPattern(WindowPattern.Pattern) as WindowPattern; window.SetWindowVisualState(WindowVisualState.Normal); //Condition panel = new PropertyCondition(AutomationElement.ClassNameProperty, "Windows.UI.Core.CoreWindow"); //AutomationElement appPanel = appElement.FindFirst(TreeScope.Children, panel); //Condition btnOneCondition = new PropertyCondition(AutomationElement.AutomationIdProperty, "num1Button"); //AutomationElement btnOne = appPanel.FindFirst(TreeScope.Descendants, btnOneCondition); //Condition btnOneCondition = new PropertyCondition(AutomationElement.AutomationIdProperty, "num1Button"); //PropertyCondition conditionCanMaximize = new PropertyCondition(WindowPattern.WindowVisualStateProperty, WindowVisualState.Normal); AutomationElement btnOne = rootElement.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.AutomationIdProperty, "num1Button")); InvokePattern btnOnePattern = btnOne.GetCurrentPattern(InvokePattern.Pattern) as InvokePattern; btnOnePattern.Invoke(); } catch (Exception Ex) { MessageBox.Show("Error in: {0}", Ex.ToString().Trim()); } }
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(); } } } } }
public void WindowPatternCachedTest() { using (AppHost host = new AppHost("notepad.exe", "")) { CacheRequest req = new CacheRequest(); req.Add(WindowPattern.Pattern); req.Add(WindowPattern.CanMaximizeProperty); req.Add(WindowPattern.CanMinimizeProperty); req.Add(WindowPattern.IsTopmostProperty); req.Add(WindowPattern.WindowInteractionStateProperty); req.Add(WindowPattern.WindowVisualStateProperty); using (req.Activate()) { AutomationElement cachedEl = host.Element.GetUpdatedCache(req); // Window Pattern WindowPattern windowPattern = (WindowPattern)cachedEl.GetCachedPattern(WindowPattern.Pattern); Assert.IsTrue(windowPattern.Cached.CanMaximize); Assert.IsTrue(windowPattern.Cached.CanMinimize); Assert.IsFalse(windowPattern.Cached.IsTopmost); Assert.AreNotEqual(windowPattern.Cached.WindowVisualState, WindowVisualState.Minimized); Assert.AreNotEqual(windowPattern.Cached.WindowInteractionState, WindowInteractionState.Closing); } } }
public void WriteNotepad() { try { Condition condition = new PropertyCondition(AutomationElement.ClassNameProperty, "Notepad"); AutomationElement appElement = rootElement.FindFirst(TreeScope.Children, condition); WindowPattern window = appElement.GetCurrentPattern(WindowPattern.Pattern) as WindowPattern; window.SetWindowVisualState(WindowVisualState.Normal); AutomationElement btnOne = rootElement.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.AutomationIdProperty, "15")); //ValuePattern ValPattern = btnOne.GetCurrentPattern(ValuePattern.Pattern) as ValuePattern; btnOne.SetFocus(); SendKeys.SendWait("Vincent Lee Flores"); //InsertText(btnOne, "enteng"); } catch (Exception Ex) { MessageBox.Show("Error in: {0}", Ex.ToString().Trim()); } }
/// <summary> /// Sets the state of the window /// </summary> /// <param name="state">The <see cref="WindowVisualState"/> of the current window</param> /// <param name="wp">The WindowPattern of the target window.</param> private static void SetState(WindowVisualState state, WindowPattern wp) { switch (state) { case WindowVisualState.Maximized: // Confirm that the element can be maximized if ((wp.Current.CanMaximize) && !(wp.Current.IsModal)) { wp.SetWindowVisualState(WindowVisualState.Maximized); } break; case WindowVisualState.Minimized: // Confirm that the element can be minimized if ((wp.Current.CanMinimize) && !(wp.Current.IsModal)) { wp.SetWindowVisualState(WindowVisualState.Minimized); } break; case WindowVisualState.Normal: wp.SetWindowVisualState(WindowVisualState.Normal); break; default: wp.SetWindowVisualState(WindowVisualState.Normal); break; } }
/// <summary> /// Паттерн закрытия окна! /// </summary> /// <param name="element"></param> public void CloseWindowPattern(AutomationElement element) { WindowPattern windowPattern = (WindowPattern)element.GetCurrentPattern(WindowPattern.Pattern); AutoItX.Sleep(2000); windowPattern.Close(); }
public void VerifyInput() { // // Start the application we are testing // string sampleAppPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase), "SampleApp.exe"); OutOfProcessSettings oops = new OutOfProcessSettings(new ProcessStartInfo(sampleAppPath), null, null); AutomatedApplication a = AutomatedApplication.Start(oops); try { a.WaitForMainWindow(TimeSpan.FromSeconds(10)); // // Discover various elements in the UI // AutomationElement inputTextBox = AutomationUtilities.FindElementsById(a.MainWindow, "inputTextBox")[0]; AutomationElement outputTextBox = AutomationUtilities.FindElementsById(a.MainWindow, "outputTextBox")[0]; AutomationElement appendButton = AutomationUtilities.FindElementsById(a.MainWindow, "appendButton")[0]; // // Click on the input text box and simulate typing // string inputText = "TestTest"; string expectedText = inputText + "\n"; WindowPattern winPattern = a.MainWindow.GetCurrentPattern(WindowPattern.Pattern) as WindowPattern; Helpers.MoveToAndClick(inputTextBox); winPattern.WaitForInputIdle(1000); Microsoft.Test.Keyboard.Type(inputText); winPattern.WaitForInputIdle(1000); // // Now click the button // Helpers.MoveToAndClick(appendButton); winPattern.WaitForInputIdle(1000); // // Now, get the text of the outputTextBox and compare it against what's expected // Fail the test if expected != actual // TextPattern textPattern = outputTextBox.GetCurrentPattern(TextPattern.Pattern) as TextPattern; string actualText = textPattern.DocumentRange.GetText(-1); // // Report the test result // Assert.AreEqual(expectedText, actualText); } finally { // // Close the tested application // a.Close(); } }
public void Close() { STAHelper.Invoke( delegate() { WindowPattern.Close(); } ); }
/// <summary> /// Gets the interaction state of the window /// </summary> /// <param name="control">The UI Automation element</param> /// <returns> /// The current <see cref="WindowInteractionState"/> /// </returns> internal static WindowInteractionState GetInteractionState(AutomationElement control) { WindowPattern pattern = (WindowPattern)CommonUIAPatternHelpers.CheckPatternSupport(WindowPattern.Pattern, control); return(false == pattern.WaitForInputIdle(10000) ? WindowInteractionState.NotResponding : pattern.Current.WindowInteractionState); }
/* * Creates the editor window. */ public EditorWindow(BaseWindow editorWindow) { this.Window = editorWindow; // Create the patterns. this.FocusPattern = (WindowPattern)this.Window.Window.GetCurrentPattern(WindowPattern.Pattern); this.SizePattern = (TransformPattern)this.Window.Window.GetCurrentPattern(TransformPattern.Pattern); }
// 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(); }
private void WindowPatternController() { WindowPattern windowPattern = (WindowPattern)PatternObject; if (MethodType == 1) { } }
public static void Minimize(AutomationElement element) { WindowPattern currentPattern = AutomationPatternHelper.GetWindowPattern(element); if (currentPattern.Current.CanMinimize) { currentPattern.SetWindowVisualState(WindowVisualState.Minimized); } }
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; }
public static void AssertReadyForUserInteraction(AutomationElement element) { WindowPattern currentPattern = AutomationPatternHelper.GetWindowPattern(element); WindowInteractionState windowInteractionState = currentPattern.Current.WindowInteractionState; if (windowInteractionState != WindowInteractionState.ReadyForUserInteraction) { throw new Exception(string.Format("Window is not ready for user interaction. State is {0}. ({1})", windowInteractionState.ToString(), element.ToString())); } }
/// <summary> /// 关闭 被测试程序. /// </summary> public void CloseApp() { Console.WriteLine("尝试关闭程序:[{0}]", APP_NAME); // 休眠指定时间. Thread.Sleep(DEFAULT_SLEEP_TIME); // 关闭被测试程序 WindowPattern wpCloseForm = (WindowPattern)testMainForm.GetCurrentPattern(WindowPattern.Pattern); wpCloseForm.Close(); }
internal static void NormalizeWindow(AutomationElement target) { object patternObject; target.TryGetCurrentPattern(WindowPattern.Pattern, out patternObject); WindowPattern wp = patternObject as WindowPattern; wp.SetWindowVisualState(WindowVisualState.Normal); Thread.Sleep(100); }
/// <summary> /// Sets the visual state of the window /// </summary> /// <param name="control">The UI Automation element</param> /// <param name="state">The <see cref="WindowVisualState"/> of the current window</param> internal static void SetVisualState(AutomationElement control, WindowVisualState state) { WindowPattern pattern = (WindowPattern)CommonUIAPatternHelpers.CheckPatternSupport(WindowPattern.Pattern, control); if (pattern.Current.WindowInteractionState != WindowInteractionState.ReadyForUserInteraction) { return; } SetState(state, pattern); ValueVerifier <WindowVisualState, WindowVisualState> .Verify(state, GetVisualState(control)); }
public void SetWindowVisualState(WindowVisualState state, bool log) { if (log) { procedureLogger.Action(string.Format("Set {0} to be {1}.", this.NameAndType, state)); } WindowPattern wp = (WindowPattern)element.GetCurrentPattern(WindowPattern.Pattern); wp.SetWindowVisualState(state); }
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 bool TryGetWindowPattern(this AutomationElement element, out WindowPattern result) { if (element.TryGetCurrentPattern(System.Windows.Automation.WindowPattern.Pattern, out var pattern)) { result = (WindowPattern)pattern; return(true); } result = null; return(false); }
/// <summary> /// /// </summary> /// <param name="elePara"></param> public WindowEvents(AT elePara) { this.elePara = elePara; try { WindowPattern = (WindowPattern)elePara.GetMe().GetCurrentPattern(WindowPattern.Pattern); } catch (Exception) { throw new Exception("Failed to get WindowEvents."); } }