GetCurrentPropertyValue() public method

public GetCurrentPropertyValue ( AutomationProperty property ) : object
property AutomationProperty
return object
Example #1
0
 // CONSIDER: This will run on our automation thread
 //           Should be OK to call MoveWindow from there - it just posts messages to the window.
 void TestMoveWindow(AutomationElement listWindow, int xOffset, int yOffset)
 {
     var hwndList = (IntPtr)(int)(listWindow.GetCurrentPropertyValue(AutomationElement.NativeWindowHandleProperty));
     var listRect = (Rect)listWindow.GetCurrentPropertyValue(AutomationElement.BoundingRectangleProperty);
     Debug.Print("Moving from {0}, {1}", listRect.X, listRect.Y);
     Win32Helper.MoveWindow(hwndList, (int)listRect.X - xOffset, (int)listRect.Y - yOffset, (int)listRect.Width, 2 * (int)listRect.Height, true);
 }
Example #2
0
        /// -------------------------------------------------------------------
        /// <summary></summary>
        /// -------------------------------------------------------------------
        internal ScrollItemPatternWrapper(AutomationElement element, string testSuite, TestPriorities priority, TypeOfControl typeOfControl, TypeOfPattern typeOfPattern, string dirResults, bool testEvents, IApplicationCommands commands)
            :
            base(element, testSuite, priority, typeOfControl, typeOfPattern, dirResults, testEvents, commands)
        {
            Comment("Creating ScrollItemTests");

            _pattern = (ScrollItemPattern)GetPattern(m_le, m_useCurrent, ScrollItemPattern.Pattern);
            if (_pattern == null)
                ThrowMe(CheckType.IncorrectElementConfiguration, Helpers.PatternNotSupported + ": ScrollItemPattern");

            // Find the ScrollPattern
            _container = m_le;

            while (_container != null && !(bool)_container.GetCurrentPropertyValue(AutomationElement.IsScrollPatternAvailableProperty))
                _container = TreeWalker.ControlViewWalker.GetParent(_container);

            // Check to see if we actual found the container of the scrollitem
            if (_container == null)
                ThrowMe(CheckType.IncorrectElementConfiguration, "Element does not have a container with ScrollPattern");

            Comment("Found scroll container: " + Library.GetUISpyLook(_container));

            _scrollPattern = (ScrollPattern)_container.GetCurrentPattern(ScrollPattern.Pattern) as ScrollPattern;

        }
Example #3
0
        /// <summary>
        /// Creates TreeNode for the AutomationElement
        /// </summary>
        public static TreeNode CreateNodeForAutomationElement(AutomationElement element, AutomationElementTreeControl parentControl)
        {
//            System.Diagnostics.Debug.WriteLine("CreateNodeForAutomationElement...");

            TreeNode node = new TreeNode(TreeHelper.GetAutomationElementTreeNodeText(element));
            node.Tag = new AutomationElementTreeNode(element, node, parentControl);

            if ((bool)element.GetCurrentPropertyValue(AutomationElement.IsContentElementProperty))
            {
                node.ForeColor = Color.Black; //.NodeFont = new Font(FontFamily.GenericSerif, 10, FontStyle.Bold);
            }
            else
            {
                node.ForeColor = Color.DarkGray;
            }


            /*************************************************/
            // this is only for test purposes, it makes the creation of each TreeNode slower
            //DateTime now = DateTime.Now;
            //DateTime endTime = now.AddMilliseconds(400);

            //while (DateTime.Now < endTime) ;
            /*************************************************/

//            System.Diagnostics.Debug.WriteLine("CreateNodeForAutomationElement EXIT");

            return node;
        }
        /// <summary>
        ///     Check to see if the specified automation element meets the requirements of the specified condition.
        /// </summary>
        /// <param name="condition">The condition to check.</param>
        /// <param name="element">The automation element to check.</param>
        /// <returns>True if the automation element meets the condition's requirements. False otherwise.</returns>
        public static bool IsMeetsRequirements(Condition condition, AutomationElement element)
        {
            var type = condition.GetType();
            if (condition == Condition.TrueCondition)
                // Always return true.
                return true;
            if (condition == Condition.FalseCondition)
                // Always returns false.
                return false;
            if (type == typeof(NotCondition))
                // Return the negation of the inner condition.
                return !IsMeetsRequirements(((NotCondition) condition).Condition, element);
            if (type == typeof(OrCondition))
                // Return true if any of the inner conditions are true.
                return ((OrCondition) condition).GetConditions().Any(inner => IsMeetsRequirements(inner, element));
            if (type == typeof(AndCondition))
                // Return true if all of the inner conditions are true.
                return ((AndCondition) condition).GetConditions().All(inner => IsMeetsRequirements(inner, element));
            if (type == typeof(StringPropertyCondition))
                // Return true if the string property condition matches.
                return ((StringPropertyCondition) condition).IsMatch(element);
            if (type == typeof(PropertyCondition)) {
                // Return true if the property condition matches.
                var propertyCondition = (PropertyCondition) condition;
                var actual = element.GetCurrentPropertyValue(propertyCondition.Property);
                var expected = propertyCondition.Value;

                Trace.WriteLine("Checking '" + AutomationPropertyHelper.ToString(actual) + "'='" + AutomationPropertyHelper.ToString(expected) + "'", "UIAutomation-ConditionHelper");
                return AutomationPropertyHelper.Equals(actual, expected);
            }
            // Don't know how to match any other conditions.
            throw new NotSupportedException("Condition '" + type + "' is not supported");
        }
Example #5
0
File: Debug.cs Project: ritro/White
 public static void LogProperties(AutomationElement element)
 {
     AutomationProperty[] automationProperties = element.GetSupportedProperties();
     foreach (AutomationProperty automationProperty in automationProperties)
     {
         Logger.Info(automationProperty.ProgrammaticName + ":" + element.GetCurrentPropertyValue(automationProperty));
     }
 }
 /// <summary>
 ///     Check if the specified automation element meets this condition's requirements.
 /// </summary>
 /// <param name="element">The element to check.</param>
 /// <returns>True if the automation element meets this condition's requirements.</returns>
 public bool IsMatch(AutomationElement element)
 {
     var actualObj = element.GetCurrentPropertyValue(Property);
     // If the element's current property value is null or not a string object, return false.
     if (actualObj == null || !(actualObj is string))
         return false;
     // Otherwise cast to strings...
     var actual = (string) actualObj;
     var expected = (string) Value;
     // ... and compare them.
     return Matcher.IsMatch(actual, expected);
 }
Example #7
0
        internal override bool AppliesTo(AutomationElement element)
        {
            // TODO: Test caching behavior
            object currentVal   = element.GetCurrentPropertyValue(property);
            object conditionVal = val;

            if (currentVal == null || conditionVal == null)
            {
                return(currentVal == conditionVal);
            }

            // Compare AutomationElements against Condition's
            // stored runtime ID array
            if (property == AEIds.LabeledByProperty ||
                property == GridItemPatternIdentifiers.ContainingGridProperty ||
                property == SelectionItemPatternIdentifiers.SelectionContainerProperty)
            {
                AutomationElement elementVal =
                    currentVal as AutomationElement;
                int [] conditionId = conditionVal as int [];
                return(currentVal != null &&
                       conditionId != null &&
                       Automation.Compare(conditionId,
                                          elementVal.GetRuntimeId()));
            }

            // For some other properties, need to reconstruct proper
            // object for comparison
            if (property == AEIds.BoundingRectangleProperty)
            {
                double [] rectArray = (double [])val;
                conditionVal = new Rect(rectArray [0],
                                        rectArray [1],
                                        rectArray [2],
                                        rectArray [3]);
            }
            else if (property == AEIds.ClickablePointProperty)
            {
                double [] pointArray = (double [])val;
                conditionVal = new Point(pointArray [0],
                                         pointArray [1]);
            }
            else if (property == AEIds.ControlTypeProperty)
            {
                conditionVal = ControlType.LookupById((int)val);
            }
            else if (property == AEIds.CultureProperty)
            {
                conditionVal = new CultureInfo((int)val);
            }

            return(ArePropertyValuesEqual(conditionVal, currentVal));
        }
Example #8
0
        public static bool Focus(AutoElem e)
        {
            if ((bool)e.GetCurrentPropertyValue(AutoElem.IsKeyboardFocusableProperty))
            {
                e.SetFocus();
                Console.WriteLine("UIA SetFocused");
                return(true);
            }
            else
            {
                Console.WriteLine("Not UIA KbdFocusable");
            }

            IntPtr ElemHwnd = new IntPtr(e.Current.NativeWindowHandle);

            if (IntPtr.Zero.Equals(ElemHwnd))
            {
                Console.WriteLine("ElemHwnd Fail");
                return(false);
            }

            int CurThd = GetCurrentThreadId();

            if (CurThd == 0)
            {
                Console.WriteLine("GetCurThd Fail");
                return(false);
            }
            int ElemThd = GetWindowThreadProcessId(ElemHwnd, out _);

            if (ElemThd == 0)
            {
                Console.WriteLine("GetElemThd Fail");
                return(false);
            }
            if (!AttachThreadInput(CurThd, ElemThd, true))
            {
                Console.WriteLine("Attach Fail");
                AttachThreadInput(CurThd, ElemThd, false);
                return(false);
            }

            GetActiveWindow();

            Console.WriteLine(GetFocus());
            int v2 = SetFocus(ElemHwnd);

            Console.WriteLine($"{v2}");

            AttachThreadInput(CurThd, ElemThd, false);
            return(v2 != 0);
        }
        internal static string GetPatterns(AutomationElement element)
        {
            var properties = element.GetSupportedProperties();

            var msg = new StringBuilder();

            msg.Append("Supported Properties:\n");
            foreach (var automationProperty in properties)
            {
                var value = element.GetCurrentPropertyValue(automationProperty);
                msg.AppendFormat(CultureInfo.InvariantCulture, "{0}: {1}\n", automationProperty.ProgrammaticName, value);
            }

            return msg.ToString();
        }
Example #10
0
        public static void GetClassName(AutomationElement autoElement, out string className, out string localizedControlType)
        {
            ValidateArgumentNonNull(autoElement, "AutomationElement argument cannot be null");  // Sanity check

            className = ""; // Initialize
            localizedControlType = "";

            // Get ClassName (edit, richedit and various flavors of each)
            className = GetClassName(autoElement);

            // get LocalizedControlType (needed for IPControl, etc.)
            localizedControlType = (string)autoElement.GetCurrentPropertyValue(AutomationElement.LocalizedControlTypeProperty);
            if (localizedControlType != null)
                localizedControlType = localizedControlType.ToUpperInvariant(); // Culture Invariant value for property
            else
                throw new InvalidOperationException("LocalizedControlType Property cannot return null");
        }
Example #11
0
        static public object GetPropertyGridValue(Core.UIItems.WindowItems.Window mainWindow, string Name)
        {
            Panel propertyView = mainWindow.Get <Panel>(SearchCriteria.ByAutomationId("propertyGrid"));

            Assert.IsNotNull(propertyView);
            System.Windows.Automation.AutomationElement elem = propertyView.GetElement(SearchCriteria.ByControlType(System.Windows.Automation.ControlType.Table));
            Assert.IsNotNull(elem);

            Core.UIItems.TableItems.Table table = new Core.UIItems.TableItems.Table(elem, new Core.UIItems.Actions.ProcessActionListener(elem));
            Assert.IsNotNull(table);

            System.Windows.Automation.AutomationElement row = table.GetElement(SearchCriteria.ByText(Name));
            Assert.IsNotNull(row);

            object obj = row.GetCurrentPropertyValue(ValuePattern.ValueProperty);

            Assert.IsNotNull(obj);
            return(obj);
        }
Example #12
0
 /*private static void OpElem(AutoElem e) {
  *
  *  /*var Center = ((Rect)last.GetCurrentPropertyValue(
  *  AutomationElement.BoundingRectangleProperty)).Center();
  *  Console.WriteLine(Center);
  *  SetCursorPos(Center);
  *  LeftClick(Center); LeftClick(Center);
  *  foreach (var i in e.GetSupportedPatterns()) {
  *      Console.WriteLine($"{i.Id}: {i.ProgrammaticName}");
  *  }
  * }*/
 public static bool Auto(AutoElem e)
 {
     if ((bool)e.GetCurrentPropertyValue(AutoElem.IsOffscreenProperty))
     {
         if (ScrollTo(e))
         {
             return(true);
         }
     }
     if (Toggle(e))
     {
         return(true);
     }
     if (Select(e))
     {
         return(true);
     }
     if (Invoke(e))
     {
         return(true);
     }
     return(false);
 }
Example #13
0
        /// -------------------------------------------------------------------
        /// <summary>
        /// Test step to get the containing table that has table pattern implemented
        /// </summary>
        /// -------------------------------------------------------------------
        void TS_GetContainTableByNavigation(AutomationElement element, out AutomationElement table, CheckType ct)
        {
            table = element;
            while (
                !(bool)table.GetCurrentPropertyValue(AutomationElement.IsTablePatternAvailableProperty)
                && element != AutomationElement.RootElement
                )
            {
                table = TreeWalker.RawViewWalker.GetParent(table);
                if (table == null)
                    ThrowMe(ct, "There were no ancestors that suupported TablePattern");
            }

            if (element == AutomationElement.RootElement)
                ThrowMe(ct, "Could not find parent element that supports TablePattern");

            Comment("Found containing table w/navigation(" + Library.GetUISpyLook(table) + ")");
            m_TestStep++;
        }
Example #14
0
        /// -------------------------------------------------------------------
        /// <summary></summary>
        /// -------------------------------------------------------------------
        void TS_GetContainGridByNavigation(AutomationElement element, out AutomationElement grid, CheckType ct)
        {
            grid = element;
            while (
                !(bool)grid.GetCurrentPropertyValue(AutomationElement.IsGridPatternAvailableProperty)
                && element != AutomationElement.RootElement
                )
            {
                grid = TreeWalker.RawViewWalker.GetParent(grid);
                if (grid == null)
                    ThrowMe(ct, "There were not ancestors that suupported GridPattern");
            }

            if (element == AutomationElement.RootElement)
                ThrowMe(ct, "Could not find parent element that supports GridPattern");

            Comment("Found containing grid w/navigation(" + Library.GetUISpyLook(grid) + ")");
            m_TestStep++;
        }
Example #15
0
 /// -------------------------------------------------------------------
 /// <summary></summary>
 /// -------------------------------------------------------------------
 bool HelperCheckBoxCurrentToggleState(AutomationElement element, ToggleState state)
 {
     Library.ValidateArgumentNonNull(element, "AutomationElement");
     return ((ToggleState)element.GetCurrentPropertyValue(TogglePattern.ToggleStateProperty) == state);
 }
Example #16
0
        /// -------------------------------------------------------------------
        /// <summary>Used by Wait*Changed methods</summary>
        /// -------------------------------------------------------------------
        bool HelperWaitVerifySelection(AutomationElement element, string expecetdValue)
        {
            Library.ValidateArgumentNonNull(element, "element");

            AutomationElement[] selection = (AutomationElement[])element.GetCurrentPropertyValue(SelectionPattern.SelectionProperty);
            if (selection.Length == 0)
                return false;
            return (selection[0].Current.Name == expecetdValue);
        }
Example #17
0
        /// -------------------------------------------------------------------
        /// <summary></summary>
        /// -------------------------------------------------------------------
        bool HelperVerifyRegistrySettingToControlValue(string key, AutomationElement element, CheckType checkType)
        {
            int regValue = (int)HelperGetKeyNameValue(key);
            switch (element.Current.ControlType.ProgrammaticName)
            {
                case "ControlType.CheckBox":
                    {
                        ToggleState ts = (ToggleState)element.GetCurrentPropertyValue(TogglePattern.ToggleStateProperty);

                        Comment("Verify that \"{0}\".ToggleState is {1}", element.Current.Name, ts.ToString());
                        return regValue == 1 ? ts == ToggleState.On : ts == ToggleState.Off;
                    }
                default:
                    ThrowMe(CheckType.Verification, "Incorrect argument");
                    break;
            }
            return false;
        }
Example #18
0
        /// -------------------------------------------------------------------
        /// <summary>Helper: Press button</summary>
        /// -------------------------------------------------------------------
        void HelperPressButton(AutomationElement element, ActionMethod actionBY, CheckType checkType)
        {
            Library.ValidateArgumentNonNull(element, "Button AutomationElement");

            string name = element.Current.Name;

            switch (actionBY)
            {
                case ActionMethod.KeyPadOnly:
                    {
                        string buffer = element.Current.AccessKey;
                        if (!string.IsNullOrEmpty(buffer))
                        {
                            // There is an access key so use it
                            Comment("Pressing keyboard access key \"" + element.Current.AccessKey + "\"");
                            Input.SendKeyboardInput(element.Current.AccessKey);
                        }
                        else
                        {
                            // No access key so set focus and press enter
                            Comment("Setting focus to \"{0}\" and pressing ENTER", element.Current.Name);
                            element.SetFocus();
                            Input.SendKeyboardInput(System.Windows.Input.Key.Enter);
                        }
                    }
                    break;
                case ActionMethod.MouseClick:
                    {
                        Comment("Moving mouse to \"" + element.Current.Name + "\" and left clicking");
                        Input.MoveToAndClick(element);
                    }
                    break;
                default:
                    {
                        if (!(bool)element.GetCurrentPropertyValue(AutomationElement.IsInvokePatternAvailableProperty))
                            ThrowMe(checkType, "Button \"" + name + "\" does not support Invoke pattern");

                        Comment("Calling InvokePattern.Invoke() on \"" + name + "\"");
                        ((InvokePattern)element.GetCurrentPattern(InvokePattern.Pattern)).Invoke();
                    }
                    break;
            }
        }
Example #19
0
        /// -------------------------------------------------------------------
        /// <summary></summary>
        /// -------------------------------------------------------------------
        void TS_CollapseMenu(AutomationElement menu, CheckType checkType)
        {
            Comment("Collapsing menu(\"{0}\")", menu.Current.Name);
            if ((ExpandCollapseState.Collapsed != (ExpandCollapseState)menu.GetCurrentPropertyValue(ExpandCollapsePattern.ExpandCollapseStateProperty)))
            {
                Input.SendKeyboardInput(System.Windows.Input.Key.Escape, true);
                Input.SendKeyboardInput(System.Windows.Input.Key.Escape, false);
            }
            Wait(WaitForMenuCollapsed, _WAIT_NORMAL_MILLISECONDS, menu, checkType);

            m_TestStep++;
        }
Example #20
0
        /// -------------------------------------------------------------------
        /// <summary>Walk the tree up from the AutoamtionElement until we find
        /// an object that supports WindowPattern.  Then move is according to the 
        /// coordinates passed in</summary>
        /// -------------------------------------------------------------------
        internal void TS_MoveElementsWindow(AutomationElement element, double newX, double newY, out Rect orginalRect, out AutomationElement windowElement, CheckType checkType)
        {
            while (
                (element != null) &&
                (!(bool)element.GetCurrentPropertyValue(AutomationElement.IsWindowPatternAvailableProperty)) &&
                (null != (element = TreeWalker.ControlViewWalker.GetParent(element)))
                )
            {
            }

            if (element == null)
                ThrowMe(checkType, "Element does not have an Ancestor that supports WindowPattern");

            windowElement = element;
            orginalRect = windowElement.Current.BoundingRectangle;

            TS_MoveElementsWindow(windowElement, newX, newY, checkType);
        }
Example #21
0
 // Must run on the UI thread.
 private void UpdateSelectedItem(AutomationElement automationElement)
 {
     SelectedItemText = (string)automationElement.GetCurrentPropertyValue(AutomationElement.NameProperty);
     SelectedItemBounds = (Rect)automationElement.GetCurrentPropertyValue(AutomationElement.BoundingRectangleProperty);
     SelectedItemChanged(this, EventArgs.Empty);
 }
 public IntPtr ToNativeWindowHandle(AutomationElement element)
 {
     var handle = (int)element.GetCurrentPropertyValue(
         AutomationElement.NativeWindowHandleProperty, true);
     return new IntPtr(handle);
 }
Example #23
0
        public static void AutomationElementFromHandle(AutomationElement element)
        {
            AutomationElement obj;
            object handle = element.GetCurrentPropertyValue(AutomationElement.NativeWindowHandleProperty);

            Dump("FromHandle(" + handle + ")", true, element);
            if ((int)handle == 0)
                try
                {
                    obj = AutomationElement.FromHandle(IntPtr.Zero);
                }
                catch (Exception exception)
                {
                    VerifyException(element, exception, typeof(ArgumentException));
                }
            else
                try
                {
                    obj = AutomationElement.FromHandle(new IntPtr((int)handle));
                }
                catch (Exception exception)
                {
                    VerifyException(element, exception, typeof(ElementNotAvailableException));
                }
        }
Example #24
0
        /// -------------------------------------------------------------------
        /// <summary></summary>
        /// -------------------------------------------------------------------
        private void TS_CollapseMenu(AutomationElement menu, CheckType checkType)
        {
            if (false == (bool)menu.GetCurrentPropertyValue(AutomationElement.IsExpandCollapsePatternAvailableProperty))
            {
                ThrowMe(checkType, "Menu does not support ExpandCollapsePattern");
            }

            int timeout = 0;

            ExpandCollapsePattern ecp = menu.GetCurrentPattern(ExpandCollapsePattern.Pattern) as ExpandCollapsePattern;
            ecp.Collapse();

            // Yikes sleep!  But we are testing events, so cannot rely on eventing to determine when we are done.
            while (ecp.Current.ExpandCollapseState != ExpandCollapseState.Collapsed && timeout < MAX_TIME)
            {
                Thread.Sleep(INCREMENT);
                timeout += INCREMENT;
            }

            m_TestStep++;
        }
        /// <summary>
        /// this will set the highlighting rectangle upon automation element.
        /// </summary>
        /// <param name="selectedElement"></param>
        private void SetHighlightingElement(AutomationElement selectedElement)
        {
            if (selectedElement == null)
                SetVisibility(false); //if we do net have selected element then hide hilightling rectangle
            else
            {
                Rect rectangle = Rect.Empty;
                try
                {
                    //we will try to get bounding rectangle
                    rectangle = (Rect)selectedElement.GetCurrentPropertyValue(AutomationElement.BoundingRectangleProperty, true);
                }
                catch (Exception ex)
                {
                    //if it failed then log exception
                    ApplicationLogger.LogException(ex);
                }

                if (rectangle != Rect.Empty)
                {
                    //if we have rectangle then set the highlighting rectangle
                    this.Location = new Drawing.Rectangle((int)rectangle.Left, (int)rectangle.Top, (int)rectangle.Width, (int)rectangle.Height);
                    SetToolTip(selectedElement);
                    SetVisibility(true);
                }
                else
                {
                    //if we don't then hide hilightting rectangle
                    SetVisibility(false);
                }
            }
        }
Example #26
0
        public static void AutomationElementGetCurrentPropertyValue(AutomationElement element)
        {
            ArrayList automationProperties = null;
            ArrayList automationPatterns = null;
            Random rnd = new Random((int)DateTime.Now.Ticks);
            PopulateAutomationElementProperties(ref automationProperties, ref automationPatterns);
            AutomationProperty property = (AutomationProperty)automationProperties[rnd.Next(automationProperties.Count - 1)];

            Dump("GetCurrentPropertyValue(" + property + ")", true, element);
            try
            {
                object obj = element.GetCurrentPropertyValue(property);
            }
            catch (Exception exception)
            {
                VerifyException(element, exception,
                  typeof(ElementNotAvailableException),
                  typeof(InvalidOperationException) /* {"Operation is not valid due to the current state of the object."}*/
                  );
            }
        }
Example #27
0
        public static List<AutomationElement> FindAll(AutomationElement root, TreeScope scope, Condition condition, int processId) {
        	return (List<AutomationElement>)STAHelper.Invoke(
        		delegate() {
		            int elementProcessId = (int)root.GetCurrentPropertyValue(AutomationElement.ProcessIdProperty);
		            if (elementProcessId != processId) {
		                // This happens when the element represents the desktop.
		                // We could just filter using the ProcessIdProperty but this searches all nodes and *then* filters, 
		                // which is incredibly slow if we're searching a lot of nodes (i.e. TreeScope is Descendant).
		                // Instead we find all direct children with the right process id and then search them inclusively.
		                // Helpfully, there's a Subtree TreeScope which does what we want
		
		                Condition processCondition = new PropertyCondition2(AutomationElement.ProcessIdProperty, processId);
		                if (scope == TreeScope.Descendants) {
		                    List<AutomationElement> roots = AutomationExtensions.FindAllRaw(root, TreeScope.Children, processCondition);
		                    List<AutomationElement> mergedResults = new List<AutomationElement>();
		                    foreach (AutomationElement currentRoot in roots)
		                        mergedResults.AddRange(FindAll(currentRoot, TreeScope.Subtree, condition, processId));
		                    return mergedResults;
		                } else {
		                    condition = (condition == null) ? processCondition : new AndCondition(condition, processCondition);
		                }
		            }
		            if (condition == null)
		                condition = Condition.TrueCondition;
		
		            return AutomationExtensions.FindAllRaw(root, scope, condition);
        		}
        	);
        }
Example #28
0
 private void ClickTheBatch(AutomationElement lstView,int batchID)
 {
     const int eachRowHeight = 19;
     int nPosition = 21 + eachRowHeight * batchID;
     System.Windows.Rect rect = (System.Windows.Rect)lstView.GetCurrentPropertyValue(AutomationElement.BoundingRectangleProperty);
     winMessenger.MouseMove((int)rect.Left + 100, (int)rect.Top + nPosition - eachRowHeight / 2);
     winMessenger.Click();
 }
Example #29
0
        public void CenterInView(AutomationElement node) {
            var treeBounds = (System.Windows.Rect)Element.GetCurrentPropertyValue(AutomationElement.BoundingRectangleProperty);
            var lowHeight = treeBounds.Height / 2 - 10;
            var highHeight = treeBounds.Height / 2 + 10;

            var scroll = Element.GetScrollPattern();
            if (!scroll.Current.VerticallyScrollable) {
                return;
            }
            scroll.SetScrollPercent(ScrollPattern.NoScroll, 0);

            while (true) {
                var nodeBounds = (System.Windows.Rect)node.GetCurrentPropertyValue(AutomationElement.BoundingRectangleProperty);
                var heightFromTop = nodeBounds.Top - treeBounds.Top;
                if (lowHeight < heightFromTop && heightFromTop < highHeight) {
                    break;
                } else if (heightFromTop >= 0 && heightFromTop < lowHeight) {
                    break;
                } else if (scroll.Current.VerticalScrollPercent == 100.0) {
                    break;
                }

                scroll.ScrollVertical(ScrollAmount.SmallIncrement);
            }
        }
Example #30
0
 public static bool In(this AutomationProperty property, AutomationElement element)
 {
     return (bool) element.GetCurrentPropertyValue(property);
 }
Example #31
0
 ToggleState GetMenuToggleState(AutomationElement menu)
 {
     // Win32 menus only know if they are toggles if they are checked, else they are off
     return ((bool)menu.GetCurrentPropertyValue(AutomationElement.IsTogglePatternAvailableProperty) ? ToggleState.On : ToggleState.Off);
 }
Example #32
0
        /// <summary>
        /// Called by a client to add a listener for pattern or custom events.
        /// </summary>
        /// <param name="eventId">A control pattern or custom event identifier.</param>
        /// <param name="element">Element on which to listen for control pattern or custom events.</param>
        /// <param name="scope">Specifies whether to listen to property changes events on the specified element, and/or its ancestors and children.</param>
        /// <param name="eventHandler">Delegate to call when the specified event occurs.</param>
        /// 
        /// <outside_see conditional="false">
        /// This API does not work inside the secure execution environment.
        /// <exception cref="System.Security.Permissions.SecurityPermission"/>
        /// </outside_see>
        public static void AddAutomationEventHandler(
            AutomationEvent eventId,
            AutomationElement element,
            TreeScope scope,
            AutomationEventHandler eventHandler
            )
        {
            Misc.ValidateArgumentNonNull(element, "element" );
            Misc.ValidateArgumentNonNull(eventHandler, "eventHandler" );
            Misc.ValidateArgument( eventId != AutomationElement.AutomationFocusChangedEvent, SRID.EventIdMustNotBeAutomationFocusChanged );
            Misc.ValidateArgument( eventId != AutomationElement.StructureChangedEvent,SRID.EventIdMustNotBeStructureChanged );
            Misc.ValidateArgument( eventId != AutomationElement.AutomationPropertyChangedEvent, SRID.EventIdMustNotBeAutomationPropertyChanged );

            if (eventId == WindowPattern.WindowClosedEvent)
            {
                // Once a window closes and the hwnd is destroyed we won't be able to determine where it was in the 
                // Automation tree; therefore only support WindowClosed events for all windows (eg. src==root and scope 
                // is descendants) or a specific WindowPattern element (src==root of a Window and scope is the element).
                // Also handle odd combinations (eg. src==specific element and scope is subtree|ancestors).

                bool paramsValidated = false;

                if ( Misc.Compare( element, AutomationElement.RootElement ) )
                {
                    // For root element need to have Descendants scope set (Note: Subtree includes Descendants)
                    if ( ( scope & TreeScope.Descendants ) == TreeScope.Descendants )
                    {
                        paramsValidated = true;
                    }
                }
                else
                {
                    // otherwise non-root elements must have the entire tree (Anscestors, Element and Descendants)...
                    if ( ( scope & ( TreeScope.Ancestors | TreeScope.Element | TreeScope.Descendants ) ) == ( TreeScope.Ancestors | TreeScope.Element | TreeScope.Descendants ) )
                    {
                        paramsValidated = true;
                    }
                    else if ( ( scope & TreeScope.Element ) == TreeScope.Element )
                    {
                        // ...OR Element where the element implements WindowPattern
                        // PRESHARP will flag this as warning 56506/6506:Parameter 'element' to this public method must be validated: A null-dereference can occur here.
                        // False positive, element is checked, see above
#pragma warning suppress 6506
                        object val = element.GetCurrentPropertyValue(AutomationElement.NativeWindowHandleProperty);
                        if ( val != null && val is int && (int)val != 0 )
                        {
                            if ( HwndProxyElementProvider.IsWindowPatternWindow( NativeMethods.HWND.Cast( new IntPtr( (int)val ) ) ) )
                            {
                                paramsValidated = true;
                            }
                        }
                    }
                }

                if ( !paramsValidated )
                {
                    throw new ArgumentException( SR.Get( SRID.ParamsNotApplicableToWindowClosedEvent ) );
                }
            }

            // Add a client-side Handler for for this event request
            EventListener l = new EventListener(eventId, scope, null, CacheRequest.CurrentUiaCacheRequest);
            ClientEventManager.AddListener(element, eventHandler, l);
        }
Example #33
0
        /// -------------------------------------------------------------------
        /// <summary></summary>
        /// -------------------------------------------------------------------
        void TS_ToggleCheckState(AutomationElement element, WaitTestState callBackOn, WaitTestState callBackOff, CheckType checkType)
        {
            Library.ValidateArgumentNonNull(element, "AutomationElement");

            ToggleState currentToggleState;
            ToggleState newToggleState;

            // Verify that control supports ToggelPattern
            if (false == (bool)element.GetCurrentPropertyValue(AutomationElement.IsTogglePatternAvailableProperty))
                ThrowMe(checkType, "Element does not support TogglePattern");

            // Get the current ToggleState
            currentToggleState = ((ToggleState)element.GetCurrentPropertyValue(TogglePattern.ToggleStateProperty));
            Comment("Current ToggleState of " + element.Current.Name + "\" is " + currentToggleState.ToString());

            // Identify the desited ToggleState after it has been Toggled
            newToggleState = currentToggleState == ToggleState.Off ? ToggleState.On : ToggleState.Off;

            // Toggle the checkbox
            ((TogglePattern)element.GetCurrentPattern(TogglePattern.Pattern)).Toggle();

            // Wait till it actually has been checked
            if (newToggleState == ToggleState.On)
                Wait(callBackOn, _WAIT_NORMAL_MILLISECONDS, CheckType.Verification);
            else
                Wait(callBackOff, _WAIT_NORMAL_MILLISECONDS, CheckType.Verification);

            m_TestStep++;
        }
Example #34
0
        /// <summary>
        /// Called by a client to add a listener for pattern or custom events.
        /// </summary>
        /// <param name="eventId">A control pattern or custom event identifier.</param>
        /// <param name="element">Element on which to listen for control pattern or custom events.</param>
        /// <param name="scope">Specifies whether to listen to property changes events on the specified element, and/or its ancestors and children.</param>
        /// <param name="eventHandler">Delegate to call when the specified event occurs.</param>
        ///
        /// <outside_see conditional="false">
        /// This API does not work inside the secure execution environment.
        /// <exception cref="System.Security.Permissions.SecurityPermission"/>
        /// </outside_see>
        public static void AddAutomationEventHandler(
            AutomationEvent eventId,
            AutomationElement element,
            TreeScope scope,
            AutomationEventHandler eventHandler
            )
        {
            Misc.ValidateArgumentNonNull(element, "element");
            Misc.ValidateArgumentNonNull(eventHandler, "eventHandler");
            Misc.ValidateArgument(eventId != AutomationElement.AutomationFocusChangedEvent, SRID.EventIdMustNotBeAutomationFocusChanged);
            Misc.ValidateArgument(eventId != AutomationElement.StructureChangedEvent, SRID.EventIdMustNotBeStructureChanged);
            Misc.ValidateArgument(eventId != AutomationElement.AutomationPropertyChangedEvent, SRID.EventIdMustNotBeAutomationPropertyChanged);

            if (eventId == WindowPattern.WindowClosedEvent)
            {
                // Once a window closes and the hwnd is destroyed we won't be able to determine where it was in the
                // Automation tree; therefore only support WindowClosed events for all windows (eg. src==root and scope
                // is descendants) or a specific WindowPattern element (src==root of a Window and scope is the element).
                // Also handle odd combinations (eg. src==specific element and scope is subtree|ancestors).

                bool paramsValidated = false;

                if (Misc.Compare(element, AutomationElement.RootElement))
                {
                    // For root element need to have Descendants scope set (Note: Subtree includes Descendants)
                    if ((scope & TreeScope.Descendants) == TreeScope.Descendants)
                    {
                        paramsValidated = true;
                    }
                }
                else
                {
                    // otherwise non-root elements must have the entire tree (Anscestors, Element and Descendants)...
                    if ((scope & (TreeScope.Ancestors | TreeScope.Element | TreeScope.Descendants)) == (TreeScope.Ancestors | TreeScope.Element | TreeScope.Descendants))
                    {
                        paramsValidated = true;
                    }
                    else if ((scope & TreeScope.Element) == TreeScope.Element)
                    {
                        // ...OR Element where the element implements WindowPattern
                        // PRESHARP will flag this as warning 56506/6506:Parameter 'element' to this public method must be validated: A null-dereference can occur here.
                        // False positive, element is checked, see above
#pragma warning suppress 6506
                        object val = element.GetCurrentPropertyValue(AutomationElement.NativeWindowHandleProperty);
                        if (val != null && val is int && (int)val != 0)
                        {
                            if (HwndProxyElementProvider.IsWindowPatternWindow(NativeMethods.HWND.Cast(new IntPtr((int)val))))
                            {
                                paramsValidated = true;
                            }
                        }
                    }
                }

                if (!paramsValidated)
                {
                    throw new ArgumentException(SR.Get(SRID.ParamsNotApplicableToWindowClosedEvent));
                }
            }

            // Add a client-side Handler for for this event request
            EventListener l = new EventListener(eventId, scope, null, CacheRequest.CurrentUiaCacheRequest);
            ClientEventManager.AddListener(element, eventHandler, l);
        }
Example #35
0
        /// -------------------------------------------------------------------
        /// <summary></summary>
        /// -------------------------------------------------------------------
        void TS_VerifyToggleState(AutomationElement element, string keyname, CheckType checkType)
        {
            if (null == element)
            {
                Console.WriteLine("**********************");
                Thread.Sleep(10000);
                ThrowMe(checkType, "element == null in TS_VerifyToggleState...could not get menu?");
            }
            int regvalue = (int)HelperGetKeyNameValue(keyname);
            Comment("Verify that the toggle state of \"" + element.Current.Name + "\" is {0}", regvalue == 1 ? "toggled" : "not toggled");

            bool toggleSupported = (bool)element.GetCurrentPropertyValue(AutomationElement.IsTogglePatternAvailableProperty);

            if (false == toggleSupported)
            {
                if (element.Current.ControlType == ControlType.MenuItem)
                {
                    // win32 menus only know thre are togglable when they are checked
                    if (regvalue == 1 ? toggleSupported != true : toggleSupported != false)
                        ThrowMe(checkType, "ToggleState was incorrect");
                }
                else
                {
                    ThrowMe(checkType, "Should support TogglePattern");
                }
            }
            else
            {
                ToggleState toggled = (ToggleState)element.GetCurrentPropertyValue(TogglePattern.ToggleStateProperty);
                if (regvalue == 1 ? toggled != ToggleState.On : toggled != ToggleState.Off)
                    ThrowMe(checkType, "ToggleState was incorrect");

            }
            m_TestStep++;
        }