Ejemplo n.º 1
0
 /// <summary>
 /// Adds a handler for property-changed event; in particular, a change in the enabled state.
 /// </summary>
 /// <param name="element">The UI Automation element whose state is being monitored.</param>
 public void SubscribePropertyChange(AutomationElement element)
 {
     Automation.AddAutomationPropertyChangedEventHandler(element,
                                                         TreeScope.Element,
                                                         propChangeHandler = new AutomationPropertyChangedEventHandler(OnPropertyChange),
                                                         AutomationElement.IsEnabledProperty);
 }
Ejemplo n.º 2
0
        /// <summary>Does the invoke hyperlink.</summary>
        /// <param name="hyperlink">The hyperlink.</param>
        /// <returns></returns>
        /// <autogeneratedoc />
        /// TODO Edit XML Comment Template for DoInvokeHyperlink
        private bool DoInvokeHyperlink(AutomationElement hyperlink)
        {
            if (hyperlink.TryGetCurrentPattern(InvokePattern.Pattern, out var patternObject))
            {
                if (patternObject is InvokePattern invoke)
                {
                    Automation.AddAutomationPropertyChangedEventHandler(
                        hyperlink
                        , TreeScope.Element
                        , (sender, args) => {
                        Logger.Debug(
                            "update: "
                            + args
                            .Property
                            .ProgrammaticName
                            + " = "
                            + args
                            .NewValue
                            );
                    }
                        , hyperlink
                        .GetSupportedProperties( )
                        );

                    Logger.Debug("yay");
                    invoke.Invoke( );
                    Thread.Sleep(2000);
                    return(true);
                }
            }

            return(false);
        }
        private void SubscribeToRangeSelectorEvents(object sender, RoutedEventArgs e)
        {
            WaitCallback callback =
                delegate
            {
                if (_alreadySubscribed)
                {
                    return;
                }
                AutomationElement windowElt = AutomationElement.FromHandle(_handle);

                // Locate this UserControl with AutomationId
                var rangeSelectorElt = windowElt.FindFirst(TreeScope.Descendants,
                                                           new PropertyCondition(
                                                               AutomationElement.AutomationIdProperty,
                                                               "ID_RangeSelector"));

                Automation.AddAutomationPropertyChangedEventHandler(rangeSelectorElt, TreeScope.Element,
                                                                    TakeActionForEvent,
                                                                    new[] { ValuePattern.ValueProperty });

                _alreadySubscribed = true;
            };

            ThreadPool.QueueUserWorkItem(callback);
            PrintMessage("Subscribed to PropertyChange events on RangeSelector");
        }
Ejemplo n.º 4
0
        ///--------------------------------------------------------------------
        /// <summary>
        /// Register for events of interest.
        /// </summary>
        ///--------------------------------------------------------------------
        private void RegisterForEvents()
        {
            // Focus changes are global; we'll get cached properties for
            // all elements that receive focus.
            focusHandler =
                new AutomationFocusChangedEventHandler(OnFocusChange);
            Automation.AddAutomationFocusChangedEventHandler(focusHandler);

            // Register for events from descendants of the root element.
            // Only the events supported by a control will be registered.
            invokeHandler = new AutomationEventHandler(OnInvoke);
            Automation.AddAutomationEventHandler(
                InvokePattern.InvokedEvent,
                targetApp,
                TreeScope.Children,
                invokeHandler);
            rangevalueHandler =
                new AutomationPropertyChangedEventHandler(OnRangeValueChange);
            Automation.AddAutomationPropertyChangedEventHandler(
                targetApp,
                TreeScope.Children,
                rangevalueHandler,
                RangeValuePattern.ValueProperty);
            selectionHandler =
                new AutomationEventHandler(OnSelectionItemSelected);
            Automation.AddAutomationEventHandler(
                SelectionItemPattern.ElementSelectedEvent,
                targetApp,
                TreeScope.Descendants,
                selectionHandler);
        }
Ejemplo n.º 5
0
        private bool HookProcess()
        {
            logger.Information($"Hooking on to {ApplicationName}...");
            if (mainWindowHandle != IntPtr.Zero)
            {
                logger.Information($"Already hooked {ApplicationName}!");
                // Already hooked
                return(true);
            }

            mainWindowHandle = FindMainProcessWindow();

            if (mainWindowHandle == IntPtr.Zero)
            {
                logger.Error($"Cannot find {ApplicationName}'s main window.");
                // Main window is lost
                return(false);
            }
            else
            {
                logger.Debug($"Hooked on to window handle {mainWindowHandle}");
            }

            try
            {
                process.EnableRaisingEvents = true;
                process.Exited   += Process_Exited;
                automationElement = AutomationElement.FromHandle(mainWindowHandle);
                Automation.AddAutomationPropertyChangedEventHandler(
                    automationElement,
                    TreeScope.Element,
                    Process_VisualStateChanged,
                    new AutomationProperty[] { WindowPattern.WindowVisualStateProperty });

                logger.Debug($"Attached event handlers for {ApplicationName} window.");

                // If not already hidden and is currently minimised, hide immediately
                var isIconic = User32.IsIconic(mainWindowHandle);
                if (windowShown && isIconic)
                {
                    logger.Information($"{ApplicationName} is already minimised, hiding now.");
                    HideMainWindow();
                }
                else
                {
                    lastWindowVisualState = (WindowVisualState)automationElement.GetCurrentPropertyValue(WindowPattern.WindowVisualStateProperty);
                }
                logger.Debug($"Set {ApplicationName} visual state as {lastWindowVisualState}.");

                icon.SetMenuEnabled(true);

                return(true);
            }
            catch (Win32Exception)
            {
                mainWindowHandle = IntPtr.Zero;
                logger.Error($"No privillages to hook to {ApplicationName}.");
                return(false);
            }
        }
        private void FindAutomationElements(object state)
        {
            var elt           = AutomationElement.FromHandle(_handle);
            var rangeSelector = elt.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.ClassNameProperty, "RangeSelector"));

            Automation.AddAutomationPropertyChangedEventHandler(rangeSelector, TreeScope.Element, (sender, args) => MessageBox.Show("Hello World" + args.OldValue), new[] { RangeValuePatternIdentifiers.ValueProperty });
        }
Ejemplo n.º 7
0
        private bool HookThunderbird()
        {
            log.Information("Hooking on to Thunderbird...");
            if (thunderbirdProcess != null && thunderbirdMainWindowHandle != IntPtr.Zero)
            {
                log.Information("Already hooked!");
                // Already hooked
                return(true);
            }

            thunderbirdProcess = Process.GetProcessesByName("thunderbird").FirstOrDefault();

            if (thunderbirdProcess == null)
            {
                log.Error("Cannot find the Thunderbird process to hook to.");
                // Hook failure, process does not exist
                return(false);
            }

            thunderbirdMainWindowHandle = FindMainThunderbirdWindow(thunderbirdProcess);

            if (thunderbirdMainWindowHandle == IntPtr.Zero)
            {
                log.Error("Cannot find Thunderbird's main window.");
                // Main window is lost (hidden)
                return(false);
            }
            else
            {
                log.Debug("Hooked on to window handle {@thunderbirdMainWindowHandle}", thunderbirdMainWindowHandle);
            }

            thunderbirdProcess.EnableRaisingEvents = true;
            thunderbirdProcess.Exited   += Thunderbird_Exited;
            thunderbirdAutomationElement = AutomationElement.FromHandle(thunderbirdMainWindowHandle);
            Automation.AddAutomationPropertyChangedEventHandler(
                thunderbirdAutomationElement,
                TreeScope.Element,
                Thunderbird_VisualStateChanged,
                new AutomationProperty[] { WindowPattern.WindowVisualStateProperty });

            log.Debug("Attached event handlers for window.");

            // If not already hidden and is currently minimised, hide immediately
            var isIconic = User32.IsIconic(thunderbirdMainWindowHandle);

            if (thunderbirdShown && isIconic)
            {
                log.Information("Thunderbird is already minimised, hiding now. {@thunderbirdShown}, {@isIconic}.", thunderbirdShown, isIconic);
                HideThunderbird();
            }
            else
            {
                lastVisualState = (WindowVisualState)thunderbirdAutomationElement.GetCurrentPropertyValue(WindowPattern.WindowVisualStateProperty);
            }
            log.Debug("Setting visual state as {@lastVisualState}.", lastVisualState);

            return(true);
        }
Ejemplo n.º 8
0
        //TODO While recording you get exception when clicking at the corner of the cell
        public override void HookEvents(UIItemEventListener eventListener)
        {
            var safeAutomationEventHandler =
                new SafeAutomationEventHandler(this, eventListener, objs => ListViewEvent.Create(this, (AutomationPropertyChangedEventArgs)objs[0]));

            handler = safeAutomationEventHandler.PropertyChange;
            Automation.AddAutomationPropertyChangedEventHandler(automationElement, TreeScope.Descendants, handler, SelectionItemPattern.IsSelectedProperty);
        }
Ejemplo n.º 9
0
 protected void SubscribePropertyChange()
 {
     Automation.AddAutomationPropertyChangedEventHandler(AddressBar,
                                                         TreeScope.Element,
                                                         _propChangeHandler = new AutomationPropertyChangedEventHandler(OnPropertyChange),
                                                         AutomationProperty.LookupById(ValuePattern.ValueProperty.Id));
     Console.WriteLine($"SubscribePropertyChange. Address: {GetCurrentUrl()}");
 }
Ejemplo n.º 10
0
        /// <summary>
        /// Initializes UI automation by finding the target form, adding event handlers,
        /// and displaying the current automation element structure.
        /// </summary>
        /// <returns>true on success; otherwise, false.</returns>
        public bool StartListening()
        {
            bool returnCode = false;
            AutomationElement rootElement = AutomationElement.RootElement;

            // Set a property condition that will be used to find the main form of the
            // target application. myTestForm is the name of the Form and in the case
            // of a WinForms control, it is also the AutomationId of the element representing the control.
            Condition cond = new PropertyCondition(AutomationElement.AutomationIdProperty, "myTestForm");

            // Find the main window of the target application.
            AutomationElement mainWindowElement = rootElement.FindFirst(TreeScope.Element | TreeScope.Children, cond);

            if (mainWindowElement == null)
            {
                MessageBox.Show("Could not find the main form for the target application.");
                returnCode = false;
            }
            else
            {
                // Find the "Show supported patterns" checkbox and add an event handler for when
                // the toggle state changes.
                AutomationElement    elementCheckBox = FindByAutomationId(mainWindowElement, "chkbxShowPatterns");
                AutomationProperty[] propsWanted     = { TogglePattern.ToggleStateProperty };

                if (elementCheckBox != null)
                {
                    if ((bool)elementCheckBox.GetCurrentPropertyValue(AutomationElement.IsTogglePatternAvailableProperty) == true)
                    {
                        IsElementToggledOn(elementCheckBox);
                        AutomationPropertyChangedEventHandler _onToggleStateChanged =
                            new AutomationPropertyChangedEventHandler(OnToggleStateChanged);
                        Automation.AddAutomationPropertyChangedEventHandler(elementCheckBox,
                                                                            TreeScope.Element,
                                                                            _onToggleStateChanged,
                                                                            propsWanted);
                    }
                }
                // Find the "UIAutomation is listening" textbox.
                listenElement = FindByAutomationId(mainWindowElement, "tbListen");

                // Find the tab control and add an event handler for when the automation tree structure changes.
                // This event will be raised whenever the user selects a tab.
                tabElement = FindByAutomationId(mainWindowElement, "tabControl1");
                if (tabElement != null)
                {
                    StructureChangedEventHandler _onStructureChanged = new StructureChangedEventHandler(onStructureChanged);
                    Automation.AddStructureChangedEventHandler(tabElement, TreeScope.Descendants, _onStructureChanged);
                }
                string StructureDescription = GetAutomationStructure(tabElement);
                ShowStructure(StructureDescription);
                // Check the "UIAutomation is listening" checkbox in the target application.
                InformTarget(true);

                returnCode = true;
            }
            return(returnCode);
        }
Ejemplo n.º 11
0
        public void Start()
        {
            _lastvalues.Clear();
            _taskbars.Clear();
            _taskbarChildren.Clear();

            // Setting up the condition to find AutomationElements
            OrCondition condition = new OrCondition(new PropertyCondition(AutomationElement.ClassNameProperty, "Shell_TrayWnd"), new PropertyCondition(AutomationElement.ClassNameProperty, "Shell_SecondaryTrayWnd"));

            // Setting up cache request
            CacheRequest cacheRequest = new CacheRequest();

            cacheRequest.Add(AutomationElement.NameProperty);
            cacheRequest.Add(AutomationElement.BoundingRectangleProperty);

            // Activating cache request
            using (cacheRequest.Activate())
            {
                // Finding tray windows
                AutomationElementCollection lists = _desktop.FindAll(TreeScope.Children, condition);
                if (lists == null)
                {
                    return;
                }

                _lastvalues.Clear();

                // Looping through all found trays
                foreach (AutomationElement trayWnd in lists)
                {
                    // Finding MSTaskListWClass
                    AutomationElement tasklist = trayWnd.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.ClassNameProperty, "MSTaskListWClass"));
                    if (tasklist == null)
                    {
                        continue;
                    }

                    // Adding an event handler on changed properties
                    Automation.AddAutomationPropertyChangedEventHandler(tasklist, TreeScope.Element, TellTrayToUpdate, AutomationElement.BoundingRectangleProperty);

                    // Saving this taskbar
                    _taskbars.Add(trayWnd);
                    // saving this taskbar AND its tasks
                    while (!_taskbarChildren.TryAdd(trayWnd, tasklist))
                    {
                    }                                                      // Ensuring it's getting added.
                }
            }

            // Adding event handlers to the desktop opening / closing.
            Automation.AddAutomationEventHandler(WindowPattern.WindowOpenedEvent, _desktop, TreeScope.Subtree, TellTrayToUpdate);
            Automation.AddAutomationEventHandler(WindowPattern.WindowClosedEvent, _desktop, TreeScope.Subtree, TellTrayToUpdate);

            // Starting taskbar thread
            _cancel        = new CancellationTokenSource();
            _taskbarThread = new Thread(new ThreadStart(taskbarLoop));
            _taskbarThread.Start();
        }
 public override void Start(IEventSink sink)
 {
     Validate.ArgumentNotNull(parameter: sink, parameterName: nameof(sink));
     Stop();
     this._sinkReference        = new WeakReference(target: sink);
     this._sinkReference.Target = sink;
     this._handlingDelegate     = Handler;
     Automation.AddAutomationPropertyChangedEventHandler(element: this._root.AutomationElement, scope: (TreeScope)this._scope, eventHandler: this._handlingDelegate, properties: this._properties);
     Log.Out(msg: "{0} Started", (object)ToString());
 }
Ejemplo n.º 13
0
 public override void HookEvents(UIItemEventListener eventListener)
 {
     handler = delegate
     {
         ActionPerformed();
         eventListener.EventOccured(new CheckBoxEvent(this));
     };
     Automation.AddAutomationPropertyChangedEventHandler(automationElement, TreeScope.Element, handler,
                                                         TogglePattern.ToggleStateProperty);
 }
Ejemplo n.º 14
0
 public override void HookEvents(UIItemEventListener eventListener)
 {
     handler = delegate(object sender, AutomationPropertyChangedEventArgs e)
     {
         if (e.NewValue.Equals(1))
         {
             return;
         }
         eventListener.EventOccured(new ListBoxEvent(this, SelectedItemText));
     };
     Automation.AddAutomationPropertyChangedEventHandler(automationElement, TreeScope.Descendants, handler, SelectionItemPattern.IsSelectedProperty);
 }
Ejemplo n.º 15
0
        private void Start()
        {
            var condition = new OrCondition(new PropertyCondition(AutomationElement.ClassNameProperty, ShellTrayWnd),
                                            new PropertyCondition(AutomationElement.ClassNameProperty, ShellSecondaryTrayWnd));
            var cacheRequest = new CacheRequest();

            cacheRequest.Add(AutomationElement.NameProperty);
            cacheRequest.Add(AutomationElement.BoundingRectangleProperty);

            _bars.Clear();
            _children.Clear();
            _lasts.Clear();

            using (cacheRequest.Activate())
            {
                var lists = Desktop.FindAll(TreeScope.Children, condition);
                if (lists == null)
                {
                    Debug.WriteLine("Null values found, aborting");
                    return;
                }

                Debug.WriteLine(lists.Count + " bar(s) detected");
                _lasts.Clear();
                Parallel.ForEach(lists.OfType <AutomationElement>(), trayWnd =>
                {
                    var taskList = trayWnd.FindFirst(TreeScope.Descendants,
                                                     new PropertyCondition(AutomationElement.ClassNameProperty, MSTaskListWClass));
                    if (taskList == null)
                    {
                        Debug.WriteLine("Null values found, aborting");
                    }
                    else
                    {
                        _propChangeHandler = OnUIAutomationEvent;
                        Automation.AddAutomationPropertyChangedEventHandler(taskList, TreeScope.Element, _propChangeHandler,
                                                                            AutomationElement.BoundingRectangleProperty);

                        _bars.Add(trayWnd);
                        _children.Add(trayWnd, taskList);

                        _positionThreads[trayWnd] = Task.Run(() => LoopForPosition(trayWnd), _loopCancellationTokenSource.Token);
                    }
                });
            }

            _uiaEventHandler = OnUIAutomationEvent;
            Automation.AddAutomationEventHandler(WindowPattern.WindowOpenedEvent, Desktop, TreeScope.Subtree, _uiaEventHandler);
            Automation.AddAutomationEventHandler(WindowPattern.WindowClosedEvent, Desktop, TreeScope.Subtree, _uiaEventHandler);

            SystemEvents.DisplaySettingsChanging += SystemEvents_DisplaySettingsChanged;
        }
Ejemplo n.º 16
0
        // </Snippet104>

        // <Snippet105>
        ///--------------------------------------------------------------------
        /// <summary>
        /// Register for automation property change events of interest.
        /// </summary>
        /// <param name="targetControl">
        /// The automation element of interest.
        /// </param>
        ///--------------------------------------------------------------------
        private void RegisterForPropertyChangedEvents(
            AutomationElement targetControl)
        {
            AutomationPropertyChangedEventHandler propertyChangeListener =
                new AutomationPropertyChangedEventHandler(
                    OnTopmostPropertyChange);

            Automation.AddAutomationPropertyChangedEventHandler(
                targetControl,
                TreeScope.Element,
                propertyChangeListener,
                WindowPattern.IsTopmostProperty);
        }
Ejemplo n.º 17
0
 public bool Hook(IntPtr windowHandle)
 {
     if (automationElement == null)
     {
         automationElement = AutomationElement.FromHandle(windowHandle);
         Automation.AddAutomationPropertyChangedEventHandler(
             automationElement,
             TreeScope.Element,
             OnVisualStateChange,
             new AutomationProperty[] { WindowPattern.WindowVisualStateProperty });
         return(true);
     }
     return(false);
 }
Ejemplo n.º 18
0
        /// <summary>
        /// Sets the event listener hook depending on event type.
        /// </summary>
        private void SetEventHook()
        {
            /* se a property change hook */
            if (_targetEvent.Property != null)
            {
                _propertyChangeHandler = OnPropertyChange;
                Automation.AddAutomationPropertyChangedEventHandler(_targetEvent.Source.UIAElement, TreeScope.Element, _propertyChangeHandler, _targetEvent.Property);
                return;
            }

            /* or a straight event handler */
            _eventHandler = OnAutomationEvent;
            Automation.AddAutomationEventHandler(_targetEvent.EventType, _targetEvent.Source.UIAElement, TreeScope.Element, _eventHandler);
        }
        private void ListeningToEvents()
        {
            IntPtr handle = new WindowInteropHelper(Application.Current.MainWindow).Handle;
            var    elt    = AutomationElement.FromHandle(handle);

            var rangeSelector = elt.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.ClassNameProperty, "RangeSelector"));

            Automation.AddAutomationPropertyChangedEventHandler(rangeSelector, TreeScope.Element,
                                                                (sender, args) =>
            {
                MessageBox.Show("Hello World" + args.OldValue);
            },
                                                                new[] { ValuePatternIdentifiers.ValueProperty });
        }
Ejemplo n.º 20
0
            /// <summary>
            /// Adds a property changed event handler
            /// </summary>
            /// <param name="element">th element for which to add the event handler</param>
            /// <param name="property">the property to track changes for</param>
            /// <param name="eventHandler">the event handler</param>
            public void AddAutomationPropertyChangedEventHandler(AutomationElement element,
                                                                 AutomationProperty property,
                                                                 AutomationPropertyChangedEventHandler eventHandler)
            {
                Log.Debug();

                try
                {
                    var events = (Hashtable)_controlElements[element];;
                    if (events == null)
                    {
                        _controlElements.Add(element, new Hashtable());
                        events = (Hashtable)_controlElements[element];
                    }

                    if (!events.Contains(property))
                    {
                        Automation.AddAutomationPropertyChangedEventHandler(element, TreeScope.Element, onPropertyChanged, property);

                        Log.Debug("Adding property changed event " + property.ProgrammaticName +
                                  ".  AutomationID: " + (element.Current.AutomationId ?? "none"));

                        var eventHandlerList = new List <AutomationPropertyChangedEventHandler>();
                        eventHandlerList.Add(eventHandler);
                        events.Add(property, eventHandlerList);
                    }
                    else
                    {
                        var eventHandlerList = (List <AutomationPropertyChangedEventHandler>)events[property];
                        if (!eventHandlerList.Contains(eventHandler))
                        {
                            Log.Debug("Registering event.  " + property.ProgrammaticName +
                                      ". AutomationID: " + (element.Current.AutomationId ?? "none"));

                            eventHandlerList.Add(eventHandler);
                        }
                        else
                        {
                            Log.Debug("Property change already registered.  " +
                                      property.ProgrammaticName + ". AutomationID: " +
                                      (element.Current.AutomationId ?? "none"));
                        }
                    }
                }
                catch (Exception e)
                {
                    Log.Exception(e);
                }
            }
Ejemplo n.º 21
0
        public void Centerlize()
        {
            Applied = true;
            PropertyCondition isShell_TrayWnd          = new PropertyCondition(AutomationElement.ClassNameProperty, Shell_TrayWnd);
            PropertyCondition isShell_SecondaryTrayWnd = new PropertyCondition(AutomationElement.ClassNameProperty, Shell_SecondaryTrayWnd);
            OrCondition       condition = new OrCondition(isShell_TrayWnd, isShell_SecondaryTrayWnd);

            CacheRequest cacheRequest = new CacheRequest();

            cacheRequest.Add(AutomationElement.NameProperty);
            cacheRequest.Add(AutomationElement.BoundingRectangleProperty);

            _bars.Clear();
            _children.Clear();
            _lasts.Clear();

            using (cacheRequest.Activate())
            {
                AutomationElementCollection elements = Desktop.FindAll(TreeScope.Children, condition);
                if (elements == null)
                {
                    return;
                }
                _lasts.Clear();

                Parallel.ForEach(elements.OfType <AutomationElement>(), trayWnd =>
                {
                    //find taskbar
                    AutomationElement taskbar = trayWnd.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.ClassNameProperty, MSTaskListWClass));
                    if (taskbar != null)
                    {
                        propertyChangedHandler = OnUIAutomationEvent;
                        Automation.AddAutomationPropertyChangedEventHandler(taskbar, TreeScope.Element, propertyChangedHandler, AutomationElement.BoundingRectangleProperty);

                        _bars.Add(trayWnd);
                        _children.Add(trayWnd, taskbar);

                        repositionThreads[trayWnd] = Task.Run(() => LoopForReposition(trayWnd), loopCancellationTokenSource.Token);
                    }
                });
            }

            automationEventHandler = OnUIAutomationEvent;
            Automation.AddAutomationEventHandler(WindowPattern.WindowOpenedEvent, Desktop, TreeScope.Subtree, automationEventHandler);
            Automation.AddAutomationEventHandler(WindowPattern.WindowClosedEvent, Desktop, TreeScope.Subtree, automationEventHandler);

            SystemEvents.DisplaySettingsChanging += SystemEvents_DisplaySettingsChanged;
        }
Ejemplo n.º 22
0
        private void Start()
        {
            OrCondition  condition    = new OrCondition(new PropertyCondition(AutomationElement.ClassNameProperty, Shell_TrayWnd), new PropertyCondition(AutomationElement.ClassNameProperty, Shell_SecondaryTrayWnd));
            CacheRequest cacheRequest = new CacheRequest();

            cacheRequest.Add(AutomationElement.NameProperty);
            cacheRequest.Add(AutomationElement.BoundingRectangleProperty);

            bars.Clear();
            children.Clear();
            lasts.Clear();

            using (cacheRequest.Activate())
            {
                AutomationElementCollection lists = desktop.FindAll(TreeScope.Children, condition);
                if (lists == null)
                {
                    Debug.WriteLine("Null values found, aborting");
                    return;
                }

                Debug.WriteLine(lists.Count + " bar(s) detected");
                lasts.Clear();
                foreach (AutomationElement trayWnd in lists)
                {
                    AutomationElement tasklist = trayWnd.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.ClassNameProperty, MSTaskListWClass));
                    if (tasklist == null)
                    {
                        Debug.WriteLine("Null values found, aborting");
                        continue;
                    }

                    propChangeHandler = new AutomationPropertyChangedEventHandler(OnUIAutomationEvent);
                    Automation.AddAutomationPropertyChangedEventHandler(tasklist, TreeScope.Element, propChangeHandler, AutomationElement.BoundingRectangleProperty);

                    bars.Add(trayWnd);
                    children.Add(trayWnd, tasklist);
                }
            }

            UIAeventHandler = new AutomationEventHandler(OnUIAutomationEvent);
            Automation.AddAutomationEventHandler(WindowPattern.WindowOpenedEvent, desktop, TreeScope.Subtree, UIAeventHandler);
            Automation.AddAutomationEventHandler(WindowPattern.WindowClosedEvent, desktop, TreeScope.Subtree, UIAeventHandler);

            positionThread = new Thread(new ThreadStart(LoopForPosition));
            positionThread.Start();
        }
Ejemplo n.º 23
0
        public void AttachToWindow(string windowName)
        {
            try
            {
                AutomationElement aeDesktop = null;
                aeDesktop = AutomationElement.RootElement;
                if (aeDesktop == null)
                {
                    throw new Exception("Unable to get Desktop");
                }

                this.m_MainWindow = null;
                int numWaits = 0;
                do
                {
                    this.m_MainWindow = aeDesktop.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.NameProperty, windowName));
                    numWaits++;
                    Thread.Sleep(200);
                }while (this.m_MainWindow == null && numWaits < 50);

                if (this.m_MainWindow == null)
                {
                    throw new Exception("Failed to find window");
                }


                AutomationProperty[] captureProperties = new AutomationProperty[]
                {
                    ValuePattern.ValueProperty,
                    TogglePattern.ToggleStateProperty,
                    SelectionPattern.SelectionProperty,
                    SelectionItemPattern.IsSelectedProperty,
                };

                Automation.AddAutomationPropertyChangedEventHandler(this.m_MainWindow, TreeScope.Subtree, this.OnPropertyChanged, captureProperties);
                Automation.AddAutomationEventHandler(SelectionPattern.InvalidatedEvent, this.m_MainWindow, TreeScope.Subtree, this.OnEvent);
                Automation.AddAutomationEventHandler(InvokePattern.InvokedEvent, this.m_MainWindow, TreeScope.Subtree, this.OnEvent);
                Automation.AddAutomationEventHandler(SelectionItemPattern.ElementSelectedEvent, this.m_MainWindow, TreeScope.Subtree, this.OnEvent);

                this.Text += $" (now attached to: ({windowName})";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Ejemplo n.º 24
0
        private void AddAutomationEvents(object sender, WindowInfoEventArgs e)
        {
            lock (this.syncObject)
            {
                if (this.hasAutomationEvents &&
                    !Runtime.Instance.Settings.PinnedSettings.HideOnMinimize)
                {
                    return;
                }

                Automation.AddAutomationPropertyChangedEventHandler(this.AutomationElement, TreeScope.Element,
                                                                    this.HideOnMinimize, WindowPattern.WindowVisualStateProperty);
                this.Shown              += this.RestoreOnShow;
                this.ApplicationExited  += this.RemoveAutomationEvents;
                this.hasAutomationEvents = true;
            }
        }
Ejemplo n.º 25
0
 public override void HookEvents(UIItemEventListener eventListener)
 {
     lastSelectedItem = SelectedItem;
     handler          = delegate(object sender, AutomationPropertyChangedEventArgs e)
     {
         if (SelectedItem == null || e.NewValue.Equals(1))
         {
             return;
         }
         if (SameListItem())
         {
             return;
         }
         lastSelectedItem = SelectedItem;
         eventListener.EventOccured(new ComboBoxEvent(this, SelectedItemText));
     };
     Automation.AddAutomationPropertyChangedEventHandler(automationElement, TreeScope.Element, handler, ExpandCollapsePattern.ExpandCollapseStateProperty);
 }
Ejemplo n.º 26
0
    private static void RegisterForEvents(AutomationElement ae,
                                          AutomationPattern ap, TreeScope ts)
    {
        if (ap.Id == WindowPattern.Pattern.Id)
        {
            // The WindowPattern Exposes an element's ability
            // to change its on-screen position or size.

            // Define an AutomationPropertyChangedEventHandler delegate to
            // listen for window moved events.
            var moveHandler =
                new AutomationPropertyChangedEventHandler(OnWindowMove);

            Automation.AddAutomationPropertyChangedEventHandler(
                ae, ts, moveHandler,
                AutomationElement.BoundingRectangleProperty);
        }
    }
Ejemplo n.º 27
0
        private void SubscribeBoundingRectangleProperty(object sender, EventArgs args)
        {
            _syncContext.Post(delegate
            {
                if (_mainWindow != null)
                {
                    Automation.RemoveAutomationPropertyChangedEventHandler(_mainWindow, LocationChanged);
                }

                WindowWatcher windowWatcher = (WindowWatcher)sender;

                if (windowWatcher.MainWindow != IntPtr.Zero)
                {
                    _mainWindow = AutomationElement.FromHandle(windowWatcher.MainWindow);
                    Automation.AddAutomationPropertyChangedEventHandler(_mainWindow, TreeScope.Element, LocationChanged, AutomationElement.BoundingRectangleProperty);
                }
            }, null);
        }
Ejemplo n.º 28
0
        /// -------------------------------------------------------------------
        /// <summary>
        /// Method that registers the event handler OnEvent()
        /// </summary>
        /// -------------------------------------------------------------------
        public void AddEventHandler(AutomationElement element, TreeScope treeScope, AutomationProperty[] properties)
        {
            base.AddEventHandler();
            StringBuilder sb      = new StringBuilder("[");
            string        divider = ", ";

            foreach (AutomationProperty prop in properties)
            {
                sb.Append(prop.ProgrammaticName);
                sb.Append(divider);
            }
            if (sb.Length > 0)
            {
                sb.Remove(sb.Length - divider.Length, divider.Length).Append("]");
            }
            Comment("Adding AddAutomationPropertyChangedEventHandler({0}, TreeScope.{1}, {2}) ControlPath = {3}", Library.GetUISpyLook(element), treeScope.ToString(), sb.ToString(), Helpers.GetXmlPathFromAutomationElement(element));
            handler = new AutomationPropertyChangedEventHandler(OnEvent);
            Automation.AddAutomationPropertyChangedEventHandler(element, treeScope, handler, properties);
        }
Ejemplo n.º 29
0
        public override void HookEvents(UIItemEventListener eventListener)
        {
            clickedTreeNodeHandler = delegate
            {
                TreeNode node = ClickedNode;
                eventListener.EventOccured((new TreeNodeClickedEvent(this, node, node.IsExpanded())));
            };

            selectedTreeNodeHandler = delegate
            {
                TreeNode node = SelectedNode;
                eventListener.EventOccured((new TreeNodeSelectEvent(this, node)));
            };

            Automation.AddAutomationPropertyChangedEventHandler(automationElement, TreeScope.Subtree, clickedTreeNodeHandler,
                                                                ExpandCollapsePatternIdentifiers.ExpandCollapseStateProperty);
            Automation.AddAutomationPropertyChangedEventHandler(automationElement, TreeScope.Subtree, selectedTreeNodeHandler,
                                                                SelectionItemPatternIdentifiers.IsSelectedProperty);
        }
Ejemplo n.º 30
0
        ///--------------------------------------------------------------------
        /// <summary>
        /// Place the initial focused element into the queue.
        /// </summary>
        /// <param name="focusedElement">
        /// The initial focused element.
        /// </param>
        ///--------------------------------------------------------------------
        //private void StartQueue(AutomationElement focusedElement)
        //{
        //    ElementStore initialElement = new ElementStore();
        //    initialElement.AutomationID = focusedElement.Current.AutomationId;
        //    initialElement.ClassName = focusedElement.Current.ClassName;
        //    initialElement.ControlType = focusedElement.Current.ControlType.ProgrammaticName;
        //    initialElement.EventID = null;
        //    initialElement.SupportedPatterns = focusedElement.GetSupportedPatterns();
        //    RegisterElementEventListeners(initialElement.SupportedPatterns, focusedElement);
        //    eventTracker.Enqueue(initialElement);
        //}

        private void RegisterElementEventListeners(AutomationPattern[] automationPatterns, AutomationElement focusedElement)
        {
            foreach (AutomationPattern automationPattern in automationPatterns)
            {
                switch (automationPattern.ProgrammaticName)
                {
                case "ScrollPatternIdentifiers.Pattern":
                    AutomationPropertyChangedEventHandler targetScrollListener =
                        new AutomationPropertyChangedEventHandler(OnTargetScrolled);
                    Automation.AddAutomationPropertyChangedEventHandler(
                        focusedElement,
                        TreeScope.Element,
                        targetScrollListener,
                        ScrollPattern.HorizontallyScrollableProperty);
                    Automation.AddAutomationPropertyChangedEventHandler(focusedElement,
                                                                        TreeScope.Element,
                                                                        targetScrollListener,
                                                                        ScrollPattern.VerticalScrollPercentProperty);
                    break;

                case "TextPatternIdentifiers.Pattern":
                    AutomationEventHandler targetTextSelectionListener = new AutomationEventHandler(OnTextSelectionChanged);
                    Automation.AddAutomationEventHandler(TextPattern.TextSelectionChangedEvent, focusedElement, TreeScope.Element, targetTextSelectionListener);
                    AutomationEventHandler targetTextChangeListener = new AutomationEventHandler(OnTextChanged);
                    Automation.AddAutomationEventHandler(TextPattern.TextChangedEvent, focusedElement, TreeScope.Descendants | TreeScope.Element, targetTextChangeListener);
                    break;

                case "RangeValuePatternIdentifiers.Pattern":
                    AutomationPropertyChangedEventHandler targetRangeValueChangeListener =
                        new AutomationPropertyChangedEventHandler(OnRangeValueChange);
                    Automation.AddAutomationPropertyChangedEventHandler(focusedElement,
                                                                        TreeScope.Element, targetRangeValueChangeListener, RangeValuePattern.ValueProperty);
                    break;

                default:
                    return;
                }
            }
        }