public bool IsTopmost() { _windowPattern = _window?.GetCurrentPattern(UIA_PatternIds.UIA_WindowPatternId) as IUIAutomationWindowPattern; if (_windowPattern == null) { return(false); } return(_windowPattern.CurrentIsTopmost != 0); }
/// <summary> /// Sets the value of the given <see cref="IUIAutomationElement"/>. /// Throws an <see cref="InvalidOperationException"/> if <paramref name="element"/> does not /// support the <see cref="IUIAutomationValuePattern"/>. /// </summary> public static void SetValue(this IUIAutomationElement element, string value) { var valuePattern = element.GetCurrentPattern <IUIAutomationValuePattern>(UIA_PatternIds.UIA_ValuePatternId); if (valuePattern != null) { RetryIfNotAvailable( pattern => pattern.SetValue(value), valuePattern); } else { throw new InvalidOperationException($"The element '{element.GetNameForExceptionMessage()}' does not support the ValuePattern."); } }
/// <summary> /// Returns true if the given <see cref="IUIAutomationElement"/> is in the <see cref="ToggleState.ToggleState_On"/> state. /// Throws an <see cref="InvalidOperationException"/> if <paramref name="element"/> does not /// support the <see cref="IUIAutomationTogglePattern"/>. /// </summary> /// <param name="element"></param> /// <returns></returns> public static bool IsToggledOn(this IUIAutomationElement element) { var togglePattern = element.GetCurrentPattern <IUIAutomationTogglePattern>(UIA_PatternIds.UIA_TogglePatternId); if (togglePattern != null) { return(RetryIfNotAvailable( pattern => pattern.CurrentToggleState == ToggleState.ToggleState_On, togglePattern)); } else { throw new InvalidOperationException($"The element '{element.GetNameForExceptionMessage()}' does not support the TogglePattern."); } }
public void Native_CaretPositionPatternSmokeTest() { CaretPositionPattern.Initialize(); var cps = (ICaretPositionPattern)_nAdvancedTextBoxElement.GetCurrentPattern(CaretPositionPattern.Pattern.Id); Assert.IsNotNull(cps); // sanity check: intial selection is none, there's no text after all Assert.AreEqual(0, cps.CurrentSelectionStart); Assert.AreEqual(0, cps.CurrentSelectionLength); // enter "abcd" and select central part of it - "bc" NSetTextAndSelection("abcd", 1, 2); Assert.AreEqual(1, cps.CurrentSelectionStart); Assert.AreEqual(2, cps.CurrentSelectionLength); // validate that selected text retrieved from TextPattern changed as expected var text = (IUIAutomationTextPattern)_nAdvancedTextBoxElement.GetCurrentPattern(TextPattern.Pattern.Id); var selectionArray = text.GetSelection(); var selection = selectionArray.GetElement(0); var selectedString = selection.GetText(-1); Assert.AreEqual("bc", selectedString); }
/// <summary> /// Collapses an <see cref="IUIAutomationElement"/>. /// Throws an <see cref="InvalidOperationException"/> if <paramref name="element"/> does not /// support the <see cref="IUIAutomationExpandCollapsePattern"/>. /// </summary> public static void Collapse(this IUIAutomationElement element) { var expandCollapsePattern = element.GetCurrentPattern <IUIAutomationExpandCollapsePattern>(UIA_PatternIds.UIA_ExpandCollapsePatternId); if (expandCollapsePattern != null) { RetryIfNotAvailable( pattern => pattern.Collapse(), expandCollapsePattern); } else { throw new InvalidOperationException($"The element '{element.GetNameForExceptionMessage()}' does not support the ExpandCollapsePattern."); } }
/// <summary> /// Selects an <see cref="IUIAutomationElement"/>. /// Throws an <see cref="InvalidOperationException"/> if <paramref name="element"/> does not /// support the <see cref="IUIAutomationSelectionItemPattern"/>. /// </summary> public static void Select(this IUIAutomationElement element) { var selectionItemPattern = element.GetCurrentPattern <IUIAutomationSelectionItemPattern>(UIA_PatternIds.UIA_SelectionItemPatternId); if (selectionItemPattern != null) { RetryIfNotAvailable( pattern => pattern.Select(), selectionItemPattern); } else { throw new InvalidOperationException($"The element '{element.GetNameForExceptionMessage()}' does not support the SelectionItemPattern."); } }
/// <summary> /// 编辑控件 /// </summary> /// <param name="element"></param> static void EditControl(IUIAutomationElement element) { if (element?.CurrentControlType != UIA_ControlTypeIds.UIA_EditControlTypeId) { return; } var pattern = (IUIAutomationValuePattern)element.GetCurrentPattern(UIA_PatternIds.UIA_ValuePatternId); if (pattern == null) { return; } Console.WriteLine(pattern.CurrentValue); pattern.SetValue("chenchang"); }
/// <summary> /// Creates a UI Automation element from the given automation element /// </summary> /// <param name="owningWindow">The owning window</param> /// <param name="hintBounds">The hint bounds</param> /// <param name="automationElement">The associated automation element</param> /// <returns>The created hint, else null if the hint could not be created</returns> private Hint CreateHint(IntPtr owningWindow, Rect hintBounds, IUIAutomationElement automationElement) { try { var invokePattern = (IUIAutomationInvokePattern)automationElement.GetCurrentPattern(UIA_PatternIds.UIA_InvokePatternId); if (invokePattern != null) { return(new UiAutomationInvokeHint(owningWindow, invokePattern, hintBounds)); } var togglePattern = (IUIAutomationTogglePattern)automationElement.GetCurrentPattern(UIA_PatternIds.UIA_TogglePatternId); if (togglePattern != null) { return(new UiAutomationToggleHint(owningWindow, togglePattern, hintBounds)); } var selectPattern = (IUIAutomationSelectionItemPattern)automationElement.GetCurrentPattern(UIA_PatternIds.UIA_SelectionItemPatternId); if (selectPattern != null) { return(new UiAutomationSelectHint(owningWindow, selectPattern, hintBounds)); } var expandCollapsePattern = (IUIAutomationExpandCollapsePattern)automationElement.GetCurrentPattern(UIA_PatternIds.UIA_ExpandCollapsePatternId); if (expandCollapsePattern != null) { return(new UiAutomationExpandCollapseHint(owningWindow, expandCollapsePattern, hintBounds)); } var valuePattern = (IUIAutomationValuePattern)automationElement.GetCurrentPattern(UIA_PatternIds.UIA_ValuePatternId); if (valuePattern != null && valuePattern.CurrentIsReadOnly == 0) { return(new UiAutomationFocusHint(owningWindow, automationElement, hintBounds)); } var rangeValuePattern = (IUIAutomationRangeValuePattern)automationElement.GetCurrentPattern(UIA_PatternIds.UIA_RangeValuePatternId); if (rangeValuePattern != null && rangeValuePattern.CurrentIsReadOnly == 0) { return(new UiAutomationFocusHint(owningWindow, automationElement, hintBounds)); } return(null); } catch (Exception) { // May have gone return(null); } }
public bool IsSelected() { object obj; pElement.GetCurrentPattern(UIA_SelectionItemPatternId, out obj); try { if (obj == null) { return(false); } IUIAutomationSelectionItemPattern selprov = obj as IUIAutomationSelectionItemPattern; bool ret; selprov.get_CurrentIsSelected(out ret); return(ret); } finally { if (obj != null) { Marshal.ReleaseComObject(obj); } } }
public void TestColorPattern() { var schema = ColorSchema.GetInstance(); // Ask for the custom pattern var colorPattern = (IColorPattern)_customElement.GetCurrentPattern(schema.PatternId); Assert.IsNotNull(colorPattern); // Call through a pattern getter var colorAsValue = colorPattern.CurrentValueAsColor; Assert.AreEqual(0xFFFF0000, (uint)colorAsValue); // Call a pattern setter colorPattern.SetValueAsColor(Convert.ToInt32(0x008000)); // Call for a custom property var colorAsValue2 = (int)_customElement.GetCurrentPropertyValue(schema.ValueAsColorProperty.PropertyId); Assert.AreEqual(0xFF008000, (uint)colorAsValue2); }
public object GetCurrentPattern(AutomationPattern pattern) { Validate.ArgumentNotNull(parameter: pattern, parameterName: nameof(pattern)); return(pattern.Wrap(element: this, pattern: IUIAutomationElement.GetCurrentPattern(patternId: pattern.Id))); }
private void timer1_Tick(object sender, EventArgs e) { if (count < 4) { title = list[count]; count++; } else { count = 0; title = list[count]; count++; } //找到QQ Process[] process = Process.GetProcessesByName("QQ"); foreach (Process p in process) { textBox1.Clear(); //從QQ產生root automation IUIAutomationElement _viveportAutomationElement = _automation.ElementFromHandle( p.MainWindowHandle); if (_viveportAutomationElement == null) { throw new InvalidOperationException("QQ must be running"); } //依據屬性名稱 找出tabbox IUIAutomationCondition conditionNote = _automation.CreatePropertyCondition( _propertyIdName, title); IUIAutomationElement _tabBoxAutomationElement = _viveportAutomationElement.FindFirst( TreeScope.TreeScope_Descendants, conditionNote); if (_tabBoxAutomationElement == null) { throw new InvalidOperationException("Could not find " + title); } //由tab找出按鍵範圍 移動游標點擊 tagPOINT point = new tagPOINT(); _tabBoxAutomationElement.GetClickablePoint(out point); Cursor.Position = new Point((int)point.x, (int)point.y); LeftClick(); Thread.Sleep(150); //找出QQ聊天室顯示框 conditionNote = _automation.CreatePropertyCondition( _propertyIdName, "消息"); IUIAutomationElement _resultTextBoxAutomationElement = _viveportAutomationElement.FindFirst( TreeScope.TreeScope_Descendants, conditionNote); if (_resultTextBoxAutomationElement == null) { throw new InvalidOperationException("Could not find 消息"); } //取出消息 UIAutomationClient.IUIAutomationLegacyIAccessiblePattern legacyPattern1 = (UIAutomationClient.IUIAutomationLegacyIAccessiblePattern)_resultTextBoxAutomationElement.GetCurrentPattern(patternId); //放到texebox List <char> list = legacyPattern1.CurrentValue.ToList(); foreach (char i in list) { if (i != '\r') { textBox1.AppendText(i.ToString()); } else { textBox1.AppendText(Environment.NewLine); } } } }
// Step 2: Find all the links of interest on the loaded page. private void buttonFindLinks_Click(object sender, EventArgs e) { checkedListBoxLinks.Items.Clear(); if (webBrowserPage.Url == null) { MessageBox.Show(this, "Please load the web page of interest.", "Link Getter", MessageBoxButtons.OK); labelLinkCount.Text = "No links found."; return; } // Get the UIA element for the webBrowser with the page of interest loaded. IUIAutomationElement elementBrowser = automation.ElementFromHandle(webBrowserPage.Handle); // Build up a cache request for all the data we need, to reduce the time it // takes to access the link data once with have the collection of links. IUIAutomationCacheRequest cacheRequest = automation.CreateCacheRequest(); cacheRequest.AddProperty(propertyIdName); cacheRequest.AddPattern(patternIdValue); cacheRequest.AddProperty(propertyIdValueValue); // Assume the links have names as expected, and we don't need to // search children of the links for names. cacheRequest.TreeScope = TreeScope.TreeScope_Element; // We want the collection of all links on the page. IUIAutomationCondition conditionControlView = automation.ControlViewCondition; IUIAutomationCondition conditionHyperlink = automation.CreatePropertyCondition( propertyIdControlType, controlTypeIdHyperlink); IUIAutomationCondition finalCondition = automation.CreateAndCondition( conditionControlView, conditionHyperlink); // TODO: Call FindAllBuildCache() in a background thread in case it takes // a while. As it is, the app UI's going to freeze. // Now get the collection of links. IUIAutomationElementArray elementArray = elementBrowser.FindAllBuildCache( TreeScope.TreeScope_Descendants, finalCondition, cacheRequest); if (elementArray != null) { // Process each returned hyperlink element. for (int idxLink = 0; idxLink < elementArray.Length; ++idxLink) { IUIAutomationElement elementLink = elementArray.GetElement(idxLink); // Despite the fact that we've got the names of the UIA links, don't // use that information here. Perhaps we will use it in the future. IUIAutomationValuePattern valuePattern = (IUIAutomationValuePattern)elementLink.GetCurrentPattern( patternIdValue); if (valuePattern != null) { // We're only interested in references the page makes to itself. string strValueLink = valuePattern.CachedValue; var index = strValueLink.IndexOf('#'); if ((index > 0) && strValueLink.StartsWith(textBoxURL.Text)) { checkedListBoxLinks.Items.Add(new LinkItem() { linkName = elementLink.CachedName, linkURL = strValueLink }); } } } } // Let's assume we'll want most of the links found. SetLinkCheckedState(true); labelLinkCount.Text = "Count of links found: " + checkedListBoxLinks.Items.Count; }
public static bool xtIsItemSelected(this IUIAutomationElement element) { _SelectionItemPattern = (IUIAutomationSelectionItemPattern)element.GetCurrentPattern(UIA_PatternIds.UIA_SelectionItemPatternId); return(_SelectionItemPattern.CurrentIsSelected == 1); // CurrentIsSelected returns int 0 or 1 for binary true/false }
public static string xtGetValue(this IUIAutomationElement element) { _LegacyIAccessiblePattern = (IUIAutomationLegacyIAccessiblePattern)element.GetCurrentPattern(UIA_PatternIds.UIA_LegacyIAccessiblePatternId); return(_LegacyIAccessiblePattern.CurrentValue); }
public static ExpandCollapseState xtGetExpandCollapseState(this IUIAutomationElement element) { _ExpandCollapsePattern = (IUIAutomationExpandCollapsePattern)element.GetCurrentPattern(UIA_PatternIds.UIA_ExpandCollapsePatternId); return(_ExpandCollapsePattern.CurrentExpandCollapseState); }
public static void xtMaximizeWindow(this IUIAutomationElement element) { _WindowPattern = (IUIAutomationWindowPattern)element.GetCurrentPattern(UIA_PatternIds.UIA_WindowPatternId); _WindowPattern.SetWindowVisualState(WindowVisualState.WindowVisualState_Maximized); }
public static void xtScrollIntoView(this IUIAutomationElement element) { _ScrollItemPattern = (IUIAutomationScrollItemPattern)element.GetCurrentPattern(UIA_PatternIds.UIA_ScrollItemPatternId); _ScrollItemPattern.ScrollIntoView(); }
public static IUIAutomationElement xtCollapse(this IUIAutomationElement element) { _ExpandCollapsePattern = (IUIAutomationExpandCollapsePattern)element.GetCurrentPattern(UIA_PatternIds.UIA_ExpandCollapsePatternId); _ExpandCollapsePattern.Collapse(); return(element); }
public static void xtExpand(this IUIAutomationElement element) { _ExpandCollapsePattern = (IUIAutomationExpandCollapsePattern)element.GetCurrentPattern(UIA_PatternIds.UIA_ExpandCollapsePatternId); _ExpandCollapsePattern.Expand(); }
public static T GetCurrentPattern <T>(this IUIAutomationElement element, int patternId) { return(RetryIfNotAvailable(e => (T)element.GetCurrentPattern(patternId), element)); }
public void Test1() { ProcessStartInfo x = new ProcessStartInfo(); x.FileName = @"C:\Windows\System32\calc.exe"; var process = Process.Start(x); process.WaitForInputIdle(); var ROOT = new CUIAutomationClass().GetRootElement(); var prc = ROOT.FindAll(TreeScope.TreeScope_Children, new CUIAutomationClass().CreateTrueCondition()); int size = prc.Length; for (int i = 0; i < prc.Length; i++) { string l = prc.GetElement(i).CurrentName; int r = prc.GetElement(i).CurrentProcessId; } ////This is how you attach to an already opened process //foreach (Process procs in Process.GetProcesses()) //{ // if (procs.ProcessName.Equals("Calculator")) // { // int ProcessID = procs.Id; // } //} IUIAutomationCondition window_cond = new CUIAutomationClass().CreatePropertyCondition(UIA_PropertyIds.UIA_NamePropertyId, "Calculator"); IUIAutomationElement window = null; int attempts = 1; while (window == null && attempts < 10) { window = ROOT.FindFirst(TreeScope.TreeScope_Children, window_cond); attempts++; } IUIAutomationCondition el_cond = new CUIAutomationClass().CreatePropertyCondition(UIA_PropertyIds.UIA_AutomationIdPropertyId, "num9Button"); IUIAutomationElement el = window.FindFirst(TreeScope.TreeScope_Descendants, el_cond); var pat = (IUIAutomationInvokePattern)el.GetCurrentPattern(UIA_PatternIds.UIA_InvokePatternId); pat.Invoke(); IUIAutomation m = new CUIAutomation(); IUIAutomationCondition hist_Cond = new CUIAutomationClass().CreatePropertyCondition(UIA_PropertyIds.UIA_AutomationIdPropertyId, "HistoryButton"); IUIAutomationElement hist_El = window.FindFirst(TreeScope.TreeScope_Descendants, hist_Cond); var y = hist_El.CurrentHelpText; int p = 0; }
/// <summary> /// DO NOT USE FOR BUTTONS. /// </summary> /// <param name="element"></param> public static void xtDoDefaultAction(this IUIAutomationElement element) { _LegacyIAccessiblePattern = (IUIAutomationLegacyIAccessiblePattern)element.GetCurrentPattern(UIA_PatternIds.UIA_LegacyIAccessiblePatternId); try { _LegacyIAccessiblePattern.DoDefaultAction(); } catch (COMException e) { } }
/// <summary> /// 日期控件操作---思路--操作日期控件成功 /// </summary> public static void Method9() { var infoBar = WinApi.FindWindow(null, "信息表选择"); var winBar = WinApi.FindWindow(null, "红字发票信息表查询条件"); var childs = WinApi.FindChildInfo(winBar); var rizhiBar = childs.Find(b => b.szWindowName == "填开日期"); var subChilds = WinApi.EnumChildWindowsCallback(rizhiBar.hWnd); WinApi.GetWindowRect(new HandleRef(null, subChilds[0].hWnd), out var rect); WinApi.ClickLocation(subChilds[0].hWnd, rect.right - rect.left - 10, 11); Thread.Sleep(1000); #region UI操作失败 //var allMaitons = AutomationElement.FromHandle(winBar) // .FindAll(System.Windows.Automation.TreeScope.Descendants, Condition.TrueCondition); //for (var i = 0; i < allMaitons.Count; i++) //{ // Console.WriteLine($"Name:{allMaitons[i].Current.Name}"); //} //allMaitons[3].TryGetCurrentPattern(InvokePattern.Pattern, out var upPt); //for (var i = 0; i < 24; i++) //{ // ((InvokePattern)upPt).Invoke(); // Thread.Sleep(500); //} //WinApi.SendMessage(dataHwnd, 12, IntPtr.Zero, "2018-01-01"); #endregion #region 采用uia方式--成功 var winBarUia = UiaHelper.GetUIAutomation().ElementFromHandle(winBar); var allUiaMations = winBarUia.FindAll(TreeScope.TreeScope_Descendants, UiaHelper.GetUIAutomation().CreateTrueCondition()); IUIAutomationElement upbtnUia = null; for (var i = 0; i < allUiaMations.Length; i++) { var mation = allUiaMations.GetElement(i); Console.WriteLine($"Num:{i}, name:{mation.CurrentName}"); if (mation.CurrentName.Contains("上一个按钮")) { upbtnUia = mation; break; } } if (upbtnUia != null) { var invokePt = (IUIAutomationLegacyIAccessiblePattern)upbtnUia.GetCurrentPattern(UIA_PatternIds .UIA_LegacyIAccessiblePatternId); for (var i = 0; i < 24; i++) { invokePt.DoDefaultAction(); Thread.Sleep(500); } } Thread.Sleep(1000); winBarUia = UiaHelper.GetUIAutomation().ElementFromHandle(winBar); allUiaMations = winBarUia.FindAll(TreeScope.TreeScope_Descendants, UiaHelper.GetUIAutomation().CreateTrueCondition()); IUIAutomationElement ttbtn = null; for (var i = 0; i < allUiaMations.Length; i++) { var mation = allUiaMations.GetElement(i); Console.WriteLine($"Num:{i}, name:{mation.CurrentName}"); if (mation.CurrentName.Contains("23")) { ttbtn = mation; break; } } //选择时间 if (ttbtn != null) { var invokePt = (IUIAutomationLegacyIAccessiblePattern)ttbtn.GetCurrentPattern(UIA_PatternIds .UIA_LegacyIAccessiblePatternId); invokePt.DoDefaultAction(); } #endregion }
public static IUIAutomationElement xtInvoke(this IUIAutomationElement element) { _InvokePattern = (IUIAutomationInvokePattern)element.GetCurrentPattern(UIA_PatternIds.UIA_InvokePatternId); try { _InvokePattern.Invoke(); } catch (COMException com) { } return(element); }
////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // GetCurrentDataFromElement() // // Get the current name from a UIA element, (incurring the time cost of various a cross-proc calls). // If the element doesn't have a name, optionally try to find a name from the children of the element // by using a TreeWalker. // // Runs on the background thread. // ////////////////////////////////////////////////////////////////////////////////////////////////////////////// private string GetCurrentDataFromElement(IUIAutomationElement element, bool fSearchLinkChildren) { string strName = null; // Call back to the target app to retrieve the bounds of the hyperlink element. tagRECT rectBounds = element.CurrentBoundingRectangle; // If we're the hyperlink has a zero-size bounding rect, ignore the element. if ((rectBounds.right > rectBounds.left) && (rectBounds.bottom > rectBounds.top)) { // Get the name of the element, (again incurring a cross-proc call). This name will often // be the text shown on the screen. string strNameFound = element.CurrentName; if ((strNameFound != null) && (strNameFound.Length > 0)) { // We have a usable name. strName = strNameFound; } else { // The hyperlink has no usable name. Consider using the name of a child element of the hyperlink. if (fSearchLinkChildren) { // Use a Tree Walker here to try to find a child element of the hyperlink // that has a name. Tree walking is a time consuming action, so would be // avoided by a shipping app if alternatives like FindFirst, FindAll, or // BuildUpdatedCache could get the required data. IUIAutomationTreeWalker controlWalker = _automation.ControlViewWalker; IUIAutomationElement elementChild = controlWalker.GetFirstChildElement(element); while (elementChild != null) { string strNameChild = elementChild.CurrentName; if ((strNameChild != null) && (strNameChild.Length > 0)) { // Use the name of this child element. strName = strNameChild; break; } // Continue to the next child element. elementChild = controlWalker.GetNextSiblingElement(elementChild); } } } } // While this sample doesn't use the destination of the hyperlink, if it wanted // to get the destination, that might be available as the Value property of the // element. The Value property is part of the Value pattern, and so is accessed // through the Value pattern. // Check first whether the element supports the Value pattern. IUIAutomationValuePattern valuePattern = (IUIAutomationValuePattern)element.GetCurrentPattern(_patternIdValue); if (valuePattern != null) { string strValue = valuePattern.CurrentValue; // This is where the destination of the link would be used... } return(strName); }
public SelectionItemPattern(IUIAutomationElement element, bool canSelectMultiple = false) { _canSelectMultiple = canSelectMultiple; _selectionItemPattern = element.GetCurrentPattern(UIA_PatternIds.UIA_SelectionItemPatternId) as IUIAutomationSelectionItemPattern; }
public SelectionPattern(IUIAutomation automation, IUIAutomationElement element) { _element = element; _automation = automation; _selectionPattern = element.GetCurrentPattern(UIA_PatternIds.UIA_SelectionPatternId) as IUIAutomationSelectionPattern; }
public Window(IUIAutomationElement window) { _window = window; _transformPattern = window?.GetCurrentPattern(UIA_PatternIds.UIA_TransformPatternId) as IUIAutomationTransformPattern; }