private void StartAppWatcher(string elementName, FindWindowMethod method)
 {
     windowElement = GetAppElement(elementName, method);
     // (...)
     // You may want to perform some actions if the watched application is already running when you start your app
     Automation.AddAutomationEventHandler(WindowPattern.WindowOpenedEvent, AutomationElement.RootElement,
                                          TreeScope.Subtree, (elm, e) => {
         AutomationElement element = elm as AutomationElement;
         try
         {
             if (element == null || element.Current.ProcessId == currentProcessId)
             {
                 return;
             }
             if (windowElement == null)
             {
                 windowElement = GetAppElement(elementName, method);
             }
             if (windowElement == null || windowElement.ProcessId != element.Current.ProcessId)
             {
                 return;
             }
             // If the Window is a MessageBox generated by the watched app, attach the handler
             if (element.Current.ClassName == "#32770")
             {
                 msgBoxButton = element.FindFirst(TreeScope.Descendants,
                                                  new PropertyCondition(AutomationElement.NameProperty, "OK"));
                 if (msgBoxButton != null && msgBoxButton.GetSupportedPatterns().Any(p => p.Equals(InvokePattern.Pattern)))
                 {
                     Automation.AddAutomationEventHandler(
                         InvokePattern.InvokedEvent, msgBoxButton, TreeScope.Element,
                         DialogButtonHandler = new AutomationEventHandler(MessageBoxButtonHandler));
                 }
             }
         }
         catch (ElementNotAvailableException) {
             // Ignore: this exception may be raised if you show a modal dialog,
             // in your own app, that blocks the execution. When the dialog is closed,
             // AutomationElement element is no longer available
         }
     });
     Automation.AddAutomationEventHandler(WindowPattern.WindowClosedEvent, AutomationElement.RootElement,
                                          TreeScope.Subtree, (elm, e) => {
         AutomationElement element = elm as AutomationElement;
         if (element == null || element.Current.ProcessId == currentProcessId || windowElement == null)
         {
             return;
         }
         if (windowElement.ProcessId == element.Current.ProcessId)
         {
             if (windowElement.MainWindowTitle == element.Current.Name)
             {
                 windowElement = null;
             }
         }
     });
 }
示例#2
0
 ///--------------------------------------------------------------------
 /// <summary>
 /// Register the target closed event listener.
 /// </summary>
 ///--------------------------------------------------------------------
 private void RegisterTargetCloseEventListener()
 {
     targetCloseListener = new AutomationEventHandler(OnTargetClosed);
     Automation.AddAutomationEventHandler(
         WindowPattern.WindowClosedEvent,
         targetApp,
         TreeScope.Element,
         targetCloseListener);
 }
示例#3
0
        public override void setUp(Ice.Current context__)
        {
            Automation.AddAutomationEventHandler(
                WindowPattern.WindowOpenedEvent,
                AutomationElement.RootElement, TreeScope.Subtree,
                OnWindowOpened);

            process = application.connect(arguments);
        }
示例#4
0
        static void Main(string[] args)
        {
            CalcAutomationClient   autoClient   = new CalcAutomationClient();
            AutomationEventHandler eventHandler = new AutomationEventHandler(autoClient.OnWindowOpenOrClose);

            Automation.AddAutomationEventHandler(WindowPattern.WindowOpenedEvent, AutomationElement.RootElement, TreeScope.Children, eventHandler);
            Process.Start("calc.exe");
            Console.ReadLine();
        }
示例#5
0
 /// <summary>
 /// Note: this method takes a LONG time (several seconds) so we don't want to do this too often.
 /// </summary>
 private static void RegisterForMenuOpened()
 {
     if (registered != root)
     {
         Automation.AddAutomationEventHandler(AutomationElement.MenuOpenedEvent, root, TreeScope.Descendants, new AutomationEventHandler(OnMenuOpened));
         Automation.AddAutomationEventHandler(AutomationElement.MenuClosedEvent, root, TreeScope.Descendants, new AutomationEventHandler(OnMenuClosed));
         registered = root;
     }
 }
 public override void Start(IEventSink sink)
 {
     Validate.ArgumentNotNull(parameter: sink, parameterName: nameof(sink));
     Stop();
     Log.Out(msg: "{0} Start", (object)ToString());
     this._sinkReference    = new WeakReference(target: sink);
     this._handlingDelegate = Handler;
     Automation.AddAutomationEventHandler(eventId: this._eventId, element: this._root.AutomationElement, scope: (TreeScope)this._scope, eventHandler: this._handlingDelegate);
 }
 public static void HeadlessSetup(int processId)
 {
     SetupWhitelist();
     handler = GetOpenWindowHandler(processId);
     Automation.AddAutomationEventHandler(
         WindowPattern.WindowOpenedEvent,
         AutomationElement.RootElement,
         TreeScope.Descendants,
         handler);
 }
示例#8
0
        /// <summary>
        /// Subscribes a window element to the window-closed event.
        /// </summary>
        /// <param name="element">The window element.</param>
        private void AddToWindowHandler(AutomationElement element)
        {
            Object windowPattern;

            if (element.TryGetCurrentPattern(WindowPattern.Pattern, out windowPattern))
            {
                Automation.AddAutomationEventHandler(WindowPattern.WindowClosedEvent, element,
                                                     TreeScope.Element, onWindowClosed);
            }
        }
示例#9
0
        private void AddSelectionEvenhandler(AutomationElement element)
        {
            TreeScope scope = TreeScope.Descendants;
            AutomationEventHandler handler = SelectionChanged;

            Automation.AddAutomationEventHandler(SelectionItemPatternIdentifiers.ElementSelectedEvent, element, scope, handler);
            Automation.AddAutomationEventHandler(SelectionItemPatternIdentifiers.ElementAddedToSelectionEvent, element, scope, handler);
            Automation.AddAutomationEventHandler(SelectionItemPatternIdentifiers.ElementRemovedFromSelectionEvent, element, scope, handler);
            Automation.AddAutomationEventHandler(SelectionPatternIdentifiers.InvalidatedEvent, element, scope, handler);
        }
示例#10
0
 /// <summary>
 /// Register an event handler for InvokedEvent on the specified element.
 /// </summary>
 /// <param name="elementButton">The automation element.</param>
 public void SubscribeToInvoke(AutomationElement elementButton)
 {
     if (elementButton != null)
     {
         Automation.AddAutomationEventHandler(InvokePattern.InvokedEvent,
              elementButton, TreeScope.Element,
              UIAeventHandler = new AutomationEventHandler(OnUIAutomationEvent));
         ElementSubscribeButton = elementButton;
     }
 }
示例#11
0
        public void RegisterButtonClickEvent(AutomationElement elementButton)
        {
            //AutomationElement ElementSubscribeButton = null;
            AutomationEventHandler UIAeventHandler;

            if (elementButton != null)
            {
                Automation.AddAutomationEventHandler(InvokePattern.InvokedEvent, elementButton, TreeScope.Element, UIAeventHandler = new AutomationEventHandler(DoButtonClickAction));
                //ElementSubscribeButton = elementButton;
            }
        }
示例#12
0
        public void StartObserver()
        {
            Automation.AddAutomationEventHandler(WindowPatternIdentifiers.WindowOpenedEvent,
                                                 AutomationElement.RootElement,
                                                 TreeScope.Descendants,
                                                 WindowOpend);

            foreach (AutomationElement explorer in FindAllExplorerWindows())
            {
                AddSelectionEvenhandler(explorer);
            }
        }
示例#13
0
 public virtual void Observe()
 {
     try
     {
         _eventHandler = new AutomationEventHandler(OnEvent);
         Automation.AddAutomationEventHandler(Event, AutomationElement.RootElement, TreeScope.Descendants, _eventHandler);
     }
     catch (Exception ex)
     {
         System.Diagnostics.Debug.Print($"{ex.Message}");
     }
 }
        // </Snippet1025>

        // <Snippet103>
        ///--------------------------------------------------------------------
        /// <summary>
        /// Subscribe to the selection events of interest.
        /// </summary>
        /// <param name="selectionContainer">
        /// Automation element that supports SelectionPattern
        /// </param>
        ///--------------------------------------------------------------------
        private void SetSelectionEventHandlers
            (AutomationElement selectionContainer)
        {
            AutomationEventHandler selectionInvalidatedHandler =
                new AutomationEventHandler(SelectionInvalidatedHandler);

            Automation.AddAutomationEventHandler(
                SelectionPattern.InvalidatedEvent,
                selectionContainer,
                TreeScope.Element,
                SelectionInvalidatedHandler);
        }
示例#15
0
 static void AddClosedHandler(IntPtr handle)
 {
     Automation.AddAutomationEventHandler(
         WindowPattern.WindowClosedEvent,
         AutomationElement.FromHandle(handle),
         TreeScope.Subtree,
         (sender, e) =>
     {
         Debug.WriteLine(handle.ToString() + " IS KILL");
         WindowClosed?.Invoke(null, new WindowEventArgs(new ProgramWindow(handle)));
     });
 }
示例#16
0
        /*
         *      the first one listens for "window opened" events
         *      this catches when the checkout window opens.
         *
         *      that way we can do 2 things:
         *      1: catch it when it closes (letting the caller know the window closed) and
         *      2: hide the "enter serial number" button because their UI for it isn't that great
         *              and we want to support silent activation anyway (by gathering the info first
         *              with our own UI)
         */
        private void    RegisterEventListeners()
        {
            Automation.AddAutomationEventHandler(
                WindowPattern.WindowOpenedEvent,
                AutomationElement.RootElement,
                TreeScope.Children,
                (sender, e) =>
            {
                AutomationElement element = sender as AutomationElement;
                string automationID       = element.Current.AutomationId;

                if (automationID != kLicenseWindowAutomationID)
                {
                    return;
                }

                i_checkoutWindID = element.GetRuntimeId();

                if (!i_showEnterSerialNumberB)
                {
                    AutomationElement licenseButton = element.FindFirst(
                        TreeScope.Descendants,
                        new PropertyCondition(AutomationElement.AutomationIdProperty, kLicenseButtonAutomationID));

                    if (licenseButton != null)
                    {
                        IntPtr hwnd       = new IntPtr(licenseButton.Current.NativeWindowHandle);
                        Control buttonRef = Control.FromHandle(hwnd);

                        HideButton_Safe(buttonRef);
                    }
                }
            });

            Automation.AddAutomationEventHandler(
                WindowPattern.WindowClosedEvent,
                AutomationElement.RootElement,
                TreeScope.Subtree,
                (sender, e) =>
            {
                WindowClosedEventArgs args = e as WindowClosedEventArgs;
                int[]                                           closingWindID = args.GetRuntimeId();

                if (i_checkoutWindID != null && closingWindID != null)
                {
                    if (Automation.Compare(closingWindID, i_checkoutWindID))
                    {
                        Array.Clear(i_checkoutWindID, 0, i_checkoutWindID.Length);
                        Paddle_CheckoutWindowClosed();
                    }
                }
            });
        }
示例#17
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;
        }
示例#18
0
        static HookUtility()
        {
            dele = new WinEventDelegate(Callback);

            foreach (uint e in Enum.GetValues(typeof(Event)))
            {
                SetWinEventHook(e, e, IntPtr.Zero, dele, 0, 0, WINEVENT_OUTOFCONTEXT);
            }

            //TODO: Cannot find way to make SetWinEventHook work well, using UI Automation for now
            //SetWinEventHook(EVENT_OBJECT_CREATE, EVENT_OBJECT_CREATE, IntPtr.Zero, dele, 0, 0, WINEVENT_OUTOFCONTEXT);
            Automation.AddAutomationEventHandler(WindowPattern.WindowOpenedEvent, AutomationElement.RootElement, TreeScope.Subtree, WindowCreated);
        }
示例#19
0
        // </Snippet103>

        // <Snippet104>
        ///--------------------------------------------------------------------
        /// <summary>
        /// Register for events of interest.
        /// </summary>
        /// <param name="targetControl">
        /// The automation element of interest.
        /// </param>
        ///--------------------------------------------------------------------
        private void RegisterForAutomationEvents(
            AutomationElement targetControl)
        {
            AutomationEventHandler eventHandler =
                new AutomationEventHandler(OnWindowOpenOrClose);

            Automation.AddAutomationEventHandler(
                WindowPattern.WindowClosedEvent,
                targetControl, TreeScope.Element, eventHandler);
            Automation.AddAutomationEventHandler(
                WindowPattern.WindowOpenedEvent,
                targetControl, TreeScope.Element, eventHandler);
        }
示例#20
0
        public WindowManager(ConfigurationManager configurationManager)
        {
            this.configurationManager = configurationManager;

            windows = new Dictionary <nint, Window>();

            Automation.AddAutomationEventHandler(WindowPattern.WindowOpenedEvent, AutomationElement.RootElement, TreeScope.Children, OnWindowOpened);

            dispatcherTimer          = new DispatcherTimer();
            dispatcherTimer.Tick    += DispatcherTimer_Tick;
            dispatcherTimer.Interval = TimeSpan.FromSeconds(10);
            dispatcherTimer.Start();
        }
        private static void StartProcessAndStartWindowWatching(Process process, Process childProcess, string processName)
        {
            childProcess.WaitForInputIdle();
            WindowWatcher.process     = process;
            WindowWatcher.processName = processName;
            RevalidateApp();

            handler = GetOpenWindowHandler(process.Id);
            Automation.AddAutomationEventHandler(
                WindowPattern.WindowOpenedEvent,
                AutomationElement.RootElement,
                TreeScope.Descendants,
                handler);
        }
示例#22
0
        public void Listen()
        {
            Automation.AddAutomationEventHandler(
                WindowPattern.WindowOpenedEvent,
                AutomationElement.RootElement,
                TreeScope.Children,
                OnWindowOpened);
            while (true)
            {
                Thread.Sleep(60000);
            }

            // Automation.RemoveAllEventHandlers();
        }
示例#23
0
        public void SatisfyEverySafeNetTokenPasswordRequest(string file, string password)
        {
            //// Source: http://stackoverflow.com/questions/17927895/automate-extended-validation-ev-code-signing
            int count = 0;

            Automation.AddAutomationEventHandler(WindowPattern.WindowOpenedEvent, AutomationElement.RootElement, TreeScope.Children, (sender, e) =>
            {
                AutomationElement element = sender as AutomationElement;
                if (element.Current.Name == "Token Logon")
                {
                    WindowPattern pattern = (WindowPattern)element.GetCurrentPattern(WindowPattern.Pattern);
                    pattern.WaitForInputIdle(10000);
                    AutomationElement edit = element.FindFirst(TreeScope.Descendants, new AndCondition(
                                                                   new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit),
                                                                   new PropertyCondition(AutomationElement.NameProperty, "Token Password:"******"OK")));

                    if (edit != null && ok != null)
                    {
                        count++;
                        ValuePattern vp = (ValuePattern)edit.GetCurrentPattern(ValuePattern.Pattern);
                        vp.SetValue(password);
                        Console.WriteLine("SafeNet window (count: " + count + " window(s)) detected. Setting password...");

                        InvokePattern ip = (InvokePattern)ok.GetCurrentPattern(InvokePattern.Pattern);
                        ip.Invoke();
                    }
                    else
                    {
                        Console.WriteLine("SafeNet window detected but not with edit and button...");
                    }
                }
            });

            bool fileExist = true;

            do
            {
                Thread.Sleep(500);
                if (!File.Exists(file))
                {
                    fileExist = false;
                }
            }while (fileExist);

            Automation.RemoveAllEventHandlers();
        }
示例#24
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);
        }
示例#25
0
        /// <summary>
        /// Registers a method that handles UI Automation events
        /// </summary>
        /// <param name="eventType">The specific event type to monitor</param>
        /// <param name="control">The control to monitor for events.</param>
        public static void RegisterEvent(AutomationEvent eventType, AutomationElement control)
        {
            _control = control;

            if (eventType.Id == InvokePattern.InvokedEvent.Id)
            {
                _eventHandler = new AutomationEventHandler(OnAutomationEvent);
                Automation.AddAutomationEventHandler(eventType, control, TreeScope.Element, _eventHandler);
                _patternEventType = eventType;
                return;
            }

            SubscribeToChildNotification(eventType, control);
        }
示例#26
0
        private AutomationElement StartApp(string app)
        {
            if (File.Exists(app))
            {
                AutomationElement targetElement;

                // Start application.
                Process p = Process.Start(app);

                //// Give application a second to startup.
                Thread.Sleep(2000);

                targetElement = AutomationElement.FromHandle(p.MainWindowHandle);
                if (targetElement == null)
                {
                    return(null);
                }
                else
                {
                    AutomationEventHandler targetClosedHandler =
                        new AutomationEventHandler(onTargetClose);
                    Automation.AddAutomationEventHandler(
                        WindowPattern.WindowClosedEvent,
                        targetElement, TreeScope.Element, targetClosedHandler);

                    // Set size and position of target.
                    TransformPattern targetTransformPattern =
                        targetElement.GetCurrentPattern(TransformPattern.Pattern)
                        as TransformPattern;
                    if (targetTransformPattern == null)
                    {
                        return(null);
                    }
                    targetTransformPattern.Resize(550, 400);
                    targetTransformPattern.Move(
                        clientWindow.Left + clientWindow.Width + 25, clientWindow.Top);

                    Output("Target started.");

                    // Return the AutomationElement
                    return(targetElement);
                }
            }
            else
            {
                Output(app + " not found.");
                return(null);
            }
        }
示例#27
0
        void WindowsExplorerDialogContextMenu_Load(object sender, EventArgs e)
        {
            AutomationElement windowElement = AutomationElement.FromHandle(_startupArg.HWnd);

            Automation.AddAutomationEventHandler(WindowPattern.WindowClosedEvent, windowElement, TreeScope.Element, onWindowClose);


            _dockScanner.Dock();

            _scannerCommon.OnLoad();

            createControlHighlight();

            _scannerCommon.GetAnimationManager().Start(_rootWidget);
        }
    private void OnLoaded(object sender, RoutedEventArgs routedEventArgs)
    {
        IntPtr windowHandle = new WindowInteropHelper(this).Handle;

        Dispatcher.Invoke(() =>
        {
            var element = AutomationElement.FromHandle(windowHandle);
            Automation.AddAutomationEventHandler(InvokePattern.InvokedEvent, element, TreeScope.Descendants,
                                                 (s, a) =>
            {
                var src = s as AutomationElement;
                Debug.WriteLine($"Invoked:{a.EventId.Id},{a.EventId.ProgrammaticName},{src.NativeElement.CurrentName}");
            });
        });
    }
示例#29
0
        static void Main(string[] args)
        {
            Automation.AddAutomationEventHandler(WindowPattern.WindowOpenedEvent, AutomationElement.RootElement, TreeScope.Subtree, (sender, e) => {
                AutomationElement src = sender as AutomationElement;
                if (src != null)
                {
                    Console.WriteLine("Class : " + src.Current.ClassName);
                    Console.WriteLine("Title : " + src.Current.Name);
                    Console.WriteLine("Handle: " + src.Current.NativeWindowHandle);
                }
            });

            Console.WriteLine("Press any key to quit...");
            Console.ReadKey(true);
        }
示例#30
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;
        }