SetFocus() 공개 메소드

public SetFocus ( ) : void
리턴 void
예제 #1
0
        public static void MouseClick(AutomationElement element)
        {
            element.ScrollToIfPossible();
            element.SetFocus();

            var clickablePoint = element.GetClickablePoint();
            Cursor.Position = new System.Drawing.Point((int)clickablePoint.X, (int)clickablePoint.Y);
            mouse_event(MOUSEEVENTLF_LEFTDOWN, 0, 0, 0, 0);
            mouse_event(MOUSEEVENTLF_LEFTUP, 0, 0, 0, 0);
        }
예제 #2
0
파일: Operate.cs 프로젝트: liuxilu/UIActrl
        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);
        }
예제 #3
0
        /// -------------------------------------------------------------------
        /// <summary></summary>
        /// -------------------------------------------------------------------
        void TS_AtteptSetFocus(AutomationElement element, Type type, CheckType checkType)
        {
            Comment("Attempt to set focus to the \"{0}\" window and expect the exception of type({1})", element.Current.Name, type.ToString());
            Exception caughtException = null;
            try
            {
                element.SetFocus();
            }
            catch (Exception exception)
            {
                caughtException = exception;
            }

            if (type == null && caughtException != null)
                ThrowMe(checkType, "Should not have gottent the exception({0})", caughtException.GetType().ToString());

            if (type != null && caughtException.GetType() != type)
                ThrowMe(checkType);

            m_TestStep++;
        }
예제 #4
0
파일: Combobox.cs 프로젝트: sganesh/cobra
 private bool SelectListItem(AutomationElement element, String itemText,
     bool verify = false)
 {
     if (element == null || String.IsNullOrEmpty(itemText))
     {
         throw new XmlRpcFaultException(123,
             "Argument cannot be null or empty.");
     }
     LogMessage("SelectListItem Element: " + element.Current.Name +
         " - Type: " + element.Current.ControlType.ProgrammaticName);
     Object pattern = null;
     AutomationElement elementItem;
     try
     {
         elementItem = utils.GetObjectHandle(element, itemText);
         if (elementItem != null)
         {
             LogMessage(elementItem.Current.Name + " : " +
                 elementItem.Current.ControlType.ProgrammaticName);
             if (verify)
             {
                 bool status = false;
                 if (elementItem.TryGetCurrentPattern(SelectionItemPattern.Pattern,
                     out pattern))
                 {
                     status = ((SelectionItemPattern)pattern).Current.IsSelected;
                 }
                 if (element.TryGetCurrentPattern(ExpandCollapsePattern.Pattern,
                     out pattern))
                 {
                     LogMessage("ExpandCollapsePattern");
                     element.SetFocus();
                     ((ExpandCollapsePattern)pattern).Collapse();
                 }
                 return status;
             }
             if (elementItem.TryGetCurrentPattern(ScrollItemPattern.Pattern,
                 out pattern))
             {
                 LogMessage("ScrollItemPattern");
                 ((ScrollItemPattern)pattern).ScrollIntoView();
             }
             if (elementItem.TryGetCurrentPattern(SelectionItemPattern.Pattern,
                 out pattern))
             {
                 LogMessage("SelectionItemPattern");
                 //((SelectionItemPattern)pattern).Select();
                 // NOTE: Work around, as the above doesn't seem to work
                 // with UIAComWrapper and UIAComWrapper is required
                 // to Edit value in Spin control
                 return utils.InternalClick(elementItem);
             }
             else if (elementItem.TryGetCurrentPattern(ExpandCollapsePattern.Pattern,
                 out pattern))
             {
                 LogMessage("ExpandCollapsePattern");
                 ((ExpandCollapsePattern)pattern).Expand();
                 element.SetFocus();
                 return true;
             }
             else
             {
                 throw new XmlRpcFaultException(123,
                     "Unsupported pattern.");
             }
         }
     }
     catch (Exception ex)
     {
         LogMessage(ex);
         if (ex is XmlRpcFaultException)
             throw;
         else
             throw new XmlRpcFaultException(123,
                 "Unhandled exception: " + ex.Message);
     }
     finally
     {
         pattern = null;
         elementItem = null;
     }
     throw new XmlRpcFaultException(123,
         "Unable to find item in the list: " + itemText);
 }
예제 #5
0
        /// -------------------------------------------------------------------
        /// <summary>
        /// Call SetFocus() and verify the it does get focus by verifying
        /// that the event does occur.  Even if you are not testing for events,
        /// we use the event handler to determine that the element got
        /// the focus.
        /// </summary>
        /// -------------------------------------------------------------------
        internal void TSC_SetFocusVerifyWithEvent(AutomationElement element, CheckType checkType)
        {
            AutomationFocusChangedEventHandler handler = null;
            bool fired = false;

            try
            {
                m_FocusEvents = new ArrayList();
                Comment("Adding AutomationFocusChangedEventHandler");
                handler = new AutomationFocusChangedEventHandler(OnFocusChanged);

                Automation.AddAutomationFocusChangedEventHandler(handler);

                Comment("Calling SetFocus() on " + Library.GetUISpyLook(element));

                // Set the notifier 
                m_NotifiedEvent.Reset();

                element.SetFocus();

                Comment("Wait 1 second for event to happen");
                m_NotifiedEvent.WaitOne(1000, false);
                Comment("Stopped waiting for event to happen");

                Comment("Calling RemoveAutomationFocusChangedEventHandler()");
                Automation.RemoveAutomationFocusChangedEventHandler(handler);
                Comment("Called RemoveAutomationFocusChangedEventHandler()");

                try
                {
                    // Lock this so we don't get anymore events fired.
#pragma warning suppress 6517
                    lock (this)
                    {
                        foreach (AutomationElement tempElement in m_FocusEvents)
                        {
                            AutomationElement el = tempElement;
                            Comment("History of events fired: " + el.Current.Name);

                            // Check to see if any of the elements are the element, or one of the children
                            while (!Automation.Compare(el, AutomationElement.RootElement) && !Automation.Compare(el, element))
                                el = TreeWalker.ControlViewWalker.GetParent(el);

                            if (Automation.Compare(el, element))
                            {
                                fired = true;
                                break;
                            }
                        }
                    }
                }
                finally
                {

                }
            }
            finally
            {

            }
            if (!fired)
                ThrowMe(CheckType.Verification, "Element or one of it's children did not fire the FocusChange event");

            m_TestStep++;
        }
예제 #6
0
        /// -------------------------------------------------------------------
        /// <summary></summary>
        /// -------------------------------------------------------------------
        internal void pattern_SetFocus(AutomationElement element, Type expectedException, CheckType checkType)
        {
            string call = "SetFocus()";
            try
            {
                Comment("Calling SetFocus(" + Library.GetUISpyLook(element) + ")");
                element.SetFocus();
                Thread.Sleep(1000);
            }
            catch (Exception actualException)
            {
                if (Library.IsCriticalException(actualException))
                    throw;


                TestException(expectedException, actualException, call, checkType);
                return;
            }
            TestNoException(expectedException, call, checkType);

        }
 /// <summary>
 /// this method will set focus to the automation element
 /// </summary>
 public static void SetFocusToElement(AutomationElement element)
 {
     if (element != null)
     {
         try
         {
             element.SetFocus();
         }
         catch (Exception ex)
         {
             ApplicationLogger.LogException(ex);
         }
     }
 }
        /// <summary> 
        /// Inserts a string into textbox control
        /// </summary> 
        /// <param name="element">A text control.</param>
        /// <param name="value">The string to be inserted.</param>
        public static void InsertText(AutomationElement element,
                                            string value)
        {
            // Validate arguments / initial setup 
            if (value == null)
                throw new ArgumentNullException(
                    "String parameter must not be null.");

            if (element == null)
                throw new ArgumentNullException(
                    "AutomationElement parameter must not be null");

            // A series of basic checks prior to attempting an insertion. 
            // 
            // Check #1: Is control enabled? 
            // An alternative to testing for static or read-only controls  
            // is to filter using  
            // PropertyCondition(AutomationElement.IsEnabledProperty, true)  
            // and exclude all read-only text controls from the collection. 
            if ( ! element.Current.IsEnabled)
            {
                throw new InvalidOperationException(
                    "The control with an AutomationID of "
                    + element.Current.AutomationId.ToString()
                    + " is not enabled");
            }

            // Once you have an instance of an AutomationElement,   
            // check if it supports the ValuePattern pattern. 
            object valuePattern = null;

            // Control does not support the ValuePattern pattern  
            // so use keyboard input to insert content. 
            // 
            // NOTE: Elements that support TextPattern  
            //       do not support ValuePattern and TextPattern 
            //       does not support setting the text of  
            //       multi-line edit or document controls. 
            //       For this reason, text input must be simulated 
            //       using one of the following methods. 
            //        
            if (!element.TryGetCurrentPattern(
                ValuePattern.Pattern, out valuePattern))
            {
                throw new InvalidOperationException(
                        "The control with an AutomationID of "
                        + element.Current.AutomationId.ToString()
                        + " does not support ValuePattern.");
            }

            // Control supports the ValuePattern pattern so we can  
            // use the SetValue method to insert content. 
            // Set focus for input functionality and begin.
            element.SetFocus();

            ((ValuePattern)valuePattern).SetValue(value);
        }
예제 #9
0
파일: AgentUtils.cs 프로젝트: nbsrujan/acat
        /// <summary>
        /// Inserts the specified string value into the control
        /// referenced by the element
        /// </summary>
        /// <param name="element">the element into which to insert text</param>
        /// <param name="value">text to insert</param>
        public static void InsertTextIntoElement(AutomationElement element, string value)
        {
            if (element == null || value == null)
            {
                return;
            }

            try
            {
                if (!element.Current.IsEnabled || !element.Current.IsKeyboardFocusable)
                {
                    Log.Debug("Control not enabled or keyboard focusable. AutomationID " + element.Current.AutomationId);
                    return;
                }

                object valuePattern;
                if (!element.TryGetCurrentPattern(ValuePattern.Pattern, out valuePattern))
                {
                    element.SetFocus();
                    SendKeys.SendWait(value);
                }
                else
                {
                    element.SetFocus();
                    ((ValuePattern)valuePattern).SetValue(value);
                }
            }
            catch (Exception ex)
            {
                Log.Debug(ex.ToString());
            }
        }
예제 #10
0
        private static void SelectItemInComboBox(AutomationElement element, String selectedItemName)
        {            
            // Get the mapped item name.
            String itemName = TestDataInfrastructure.GetControlId(selectedItemName);

            // Set focus to ensure that the object is selected.
            element.SetFocus();

            // Expand the ComboBox using ExpandCollapsePattern.
            ExpandCollapsePattern expandPattern = element.GetCurrentPattern(ExpandCollapsePattern.Pattern) as ExpandCollapsePattern;
            expandPattern.Expand();

            // get the desired automation element
            PropertyCondition itemNameCondition = new PropertyCondition(AutomationElement.NameProperty, itemName);
            PropertyCondition itemTypeCondition = new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.ListItem);
            AndCondition itemCondition = new AndCondition(itemNameCondition, itemTypeCondition);

            AutomationElement item = element.FindFirst(TreeScope.Descendants, itemCondition);
            if (item != null)
            {
                // select combo box item
                ((SelectionItemPattern)item.GetCurrentPattern(SelectionItemPattern.Pattern)).Select();
            }
        }
예제 #11
0
        public void DoOperations()
        {
            //Process[] p = Process.GetProcessesByName("mmc");

            //System.Windows.Automation.AutomationElement t = WinFormAdapter.GetAEFromHandle(p[0].MainWindowHandle);
            //System.Windows.Automation.AutomationElement _0 = AutomationElement.FromHandle(p[0].MainWindowHandle);

            //System.Windows.Automation.AutomationElement t1 = WinFormAdapter.GetAEOnChildByName(t, "Sesión A - [24 x 80]");
            //System.Windows.Automation.AutomationElement t1 = t.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.NameProperty, "Inicio de sesión de IBM i"));

            //TODO: Obtener por tipo de elemento (Tipo.Edit)
            //Al tener el mismo nombre tanto el label como el textbox de un campo, toma los dos, al parecer el segundo siempre es el textbox....

            Process px = Process.Start(@"C:\Windows\System32\calc.exe");


            AutomationElement aeDesktop = AutomationElement.RootElement;

            Process[] p = Process.GetProcessesByName("calc");

            //System.Windows.Automation.AutomationElement t = WinFormAdapter.GetAEFromHandle(p[0].MainWindowHandle);
            System.Windows.Automation.AutomationElement aeCalculator = AutomationElement.FromHandle(p[0].MainWindowHandle);


            //AutomationElement aeCalculator;



            int numwaits = 0;

            do
            {
                Debug.WriteLine("Looking for Calculator . . . ");
                //aeCalculator = aeDesktop.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.NameProperty, "Calculadora"));
                numwaits += 1;
                //Thread.Sleep(100)
            } while (numwaits == null && numwaits < 50);



            String btn5hexID     = "00000087";
            String btn5decimalID = Convert.ToInt32("00000087", 16).ToString();

            String btnAddhexID     = "0000005D";
            String btnAdddecimalID = Convert.ToInt32("0000005D", 16).ToString();

            String btnEqualshexID     = "00000079";
            String btnEqualsdecimalID = Convert.ToInt32("00000079", 16).ToString();

            AutomationElement ae5Btn = aeCalculator.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.AutomationIdProperty, btn5decimalID));

            AutomationElement aeAddBtn = aeCalculator.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.AutomationIdProperty, btnAdddecimalID));

            AutomationElement aeEqualsBtn = aeCalculator.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.AutomationIdProperty, btnEqualsdecimalID));



            InvokePattern ipClick5Btn      = (InvokePattern)ae5Btn.GetCurrentPattern(InvokePattern.Pattern);
            InvokePattern ipClickAddBtn    = (InvokePattern)aeAddBtn.GetCurrentPattern(InvokePattern.Pattern);
            InvokePattern ipClickEqualsBtn = (InvokePattern)aeEqualsBtn.GetCurrentPattern(InvokePattern.Pattern);

            aeCalculator.SetFocus();
            ipClick5Btn.Invoke();
            ipClickAddBtn.Invoke();
            ipClick5Btn.Invoke();
            ipClickEqualsBtn.Invoke();



            /*
             *
             * System.Windows.Automation.AutomationElementCollection x = _0.FindAll(TreeScope.Descendants, new PropertyCondition(AutomationElement.NameProperty, "Servicios (locales)"));
             *
             * System.Windows.Automation.AutomationElementCollection xx = x[0].FindAll(TreeScope.Descendants, new PropertyCondition(AutomationElement.NameProperty, "Web Teller -  Ruteos "));
             * System.Windows.Automation.AutomationElementCollection x2 = _0.FindAll(TreeScope.Descendants, new PropertyCondition(AutomationElement.NameProperty, "Web Teller -  Ruteos "));
             * System.Windows.Automation.AutomationElementCollection x3 = _0.FindAll(TreeScope.Children, new PropertyCondition(AutomationElement.NameProperty, "Web Teller -  Ruteos "));
             * System.Windows.Automation.AutomationElementCollection x4 = _0.FindAll(TreeScope.Element, new PropertyCondition(AutomationElement.NameProperty, "Web Teller -  Ruteos "));
             *
             * System.Windows.Automation.AutomationElement y = WinFormAdapter.GetAEOnDescByName(x[0], ControlType.Edit, "Web Teller -  Ruteos ");
             * System.Windows.Automation.AutomationElement y1 = WinFormAdapter.GetAEOnDescByName(xx[0], ControlType.Edit, "Web Teller -  Ruteos ");
             *
             *
             * InvokePattern eee = (InvokePattern)y.GetCurrentPattern(InvokePattern.Pattern);
             * InvokePattern eee2 = (InvokePattern)y1.GetCurrentPattern(InvokePattern.Pattern);
             *
             *
             * eee.Invoke();
             * eee2.Invoke();
             *
             * System.Windows.Automation.AutomationElement y2 = WinFormAdapter.GetAEOnDescByName(xx[1], ControlType.Edit, "Web Teller -  Ruteos ");
             * System.Windows.Automation.AutomationElement y3 = WinFormAdapter.GetAEOnDescByName(xx[2], ControlType.Edit, "Web Teller -  Ruteos ");
             * System.Windows.Automation.AutomationElement y4 = WinFormAdapter.GetAEOnDescByName(x3[0], ControlType.Edit, "Web Teller -  Ruteos ");
             * System.Windows.Automation.AutomationElement y5 = WinFormAdapter.GetAEOnDescByName(x3[1], ControlType.Edit, "Web Teller -  Ruteos ");
             * System.Windows.Automation.AutomationElement y6 = WinFormAdapter.GetAEOnDescByName(x3[2], ControlType.Edit, "Web Teller -  Ruteos ");
             *
             *
             *
             *
             * WinFormAdapter.ClickElement(y);
             * WinFormAdapter.ClickElement(y1);
             *
             * WinFormAdapter.ClickElement(xx[2]);
             * WinFormAdapter.ClickElement(xx[1]);
             * WinFormAdapter.ClickElement(xx[0]);
             *
             */
            //x[0].FindAll(TreeScope.Children, new PropertyCondition(AutomationElement.NameProperty, ""));


            /*System.Windows.Automation.AutomationElementCollection x1 = _0.FindAll(TreeScope.Children, new PropertyCondition(AutomationElement.NameProperty, "Servicios (locales)"));
             *
             * System.Windows.Automation.AutomationElementCollection x2 = _0.FindAll(TreeScope.Descendants, new PropertyCondition(AutomationElement.NameProperty, "Área de trabajo"));
             * System.Windows.Automation.AutomationElementCollection x3 = _0.FindAll(TreeScope.Children, new PropertyCondition(AutomationElement.NameProperty, "Área de trabajo"));
             */

            /*System.Windows.Automation.AutomationElementCollection _0_Descendants_1 = _0.FindAll(TreeScope.Descendants, new PropertyCondition(AutomationElement.NameProperty, "Servicios"));
             *
             * System.Windows.Automation.AutomationElementCollection _0_Childs_1 = _0.FindAll(TreeScope.Children, new PropertyCondition(AutomationElement.NameProperty, "Servicios"));
             *
             *
             * WinFormAdapter.SetText(_0_Descendants_1[1], "BFPJUARUI");
             *
             * System.Windows.Automation.AutomationElementCollection _0_Descendants_2 = _0.FindAll(TreeScope.Descendants, new PropertyCondition(AutomationElement.NameProperty, "Contraseña:"));
             * WinFormAdapter.SetText(_0_Descendants_2[1], "BFPJUARUI2");
             *
             * WinFormAdapter.ClickElement(WinFormAdapter.GetAEOnDescByName(_0, "Aceptar"));*/
        }
 /// <summary>
 /// Set Focus
 /// </summary>
 /// <param name="automationElement">Automation Element object</param>
 /// <returns>successed 1, unsuccesse 0</returns>
 public int SetFocus(AutomationElement automationElement)
 {
     try
     {
         automationElement.SetFocus();
         return 1;
         //this.ReturnResult("1");
     }
     catch (Exception e)
     {
         Console.WriteLine(e.Message);
         return 0;
         //this.ReturnResult(e.Message);
     }
 }
예제 #13
0
        /// <summary>
        /// This function is used get target window controltype.window from all available windows in desktop.
        /// </summary>
        /// <param name="searchBy">Should be either automationid, text(Name in UI spy),helptext(tooltip over object)  or index</param>
        /// <param name="searchValue">Value for the automationid, text(Name in UI spy) or index passed in searchby parameter.</param>
        /// <param name="index">Ordinal identifier when test object or automation element does not have automationid text, or helptext</param>
        /// <returns></returns>
        public AutomationElement GetUIAutomationWindow(string searchBy, string searchValue)
        {
            bool windowsearch = true;
            if (uiAutomationWindow != null && uiAutomationCurrentParent != null)
            {
                uiAutomationCurrentParent = uiAutomationWindow;
                if ((uiAutomationWindow.Current.Name.ToLower().Contains(searchValue.ToLower())) || (uiAutomationWindow.Current.AutomationId == searchValue.ToLower()))
                {
                    logTofile(_eLogPtah, "[GetUIAutomationWindow]:---> seaching same MasterParentWindow was Avaoided to save time !!  " + uiAutomationWindow.Current.Name.ToLower() + "--" + searchValue.ToLower());
                    windowsearch = false;
                }
            }

            if (windowsearch == true)
            { // start of First IF
                logTofile(_eLogPtah, "[GetUIAutomationWindow]:---> Section :---> searching for Parent Window :  ");
                try
                { //Start of Try
                    logTofile(_eLogPtah, "[GetUIAutomationWindow]:---> Inside Try   ");
                    //    int numwait = 0;
                    switch (searchBy.ToLower())
                    { //Start of Switch
                        case "name":
                        case "text":
                        case "title":
                            { //start of case title
                                logTofile(_eLogPtah, "using  title criteria:  " + searchValue);
                                uiAutomationWindow = GetWindowByName(searchValue);
                                if (uiAutomationWindow == null)
                                {
                                    logTofile(_eLogPtah, "Searching window using collection and contains");
                                    for (var i = 0; i < _Attempts; i++)
                                    {
                                        System.Threading.Thread.Sleep(1);
                                        logTofile(_eLogPtah, "Searched for " + i.ToString() + " times");

                                        uiAutomationWindow = GetWindowByPartialName(searchValue);

                                        if (uiAutomationWindow != null)
                                        {
                                            break;
                                        }
                                    }

                                }
                                if (uiAutomationWindow != null)
                                {
                                    logTofile(_eLogPtah, "window : " + uiAutomationWindow.Current.Name.ToString());
                                }
                                else
                                {
                                    logTofile(_eLogPtah, "Window with Title: " + searchValue + "was not found");
                                }
                                if (UseWhite == true)
                                {
                                    //wpfapp._application = _application;
                                    //try
                                    //{
                                    //    _globalWindow = wpfapp.GetWPFWindow(searchValue.Trim());
                                    //}
                                    //catch (Exception e)
                                    //{
                                    //    logTofile(_eLogPtah, "exception in getwpfwidow was :" + e.Message);
                                    //}
                                }
                                else
                                {
                                    logTofile(_eLogPtah, "White window not initialized");
                                }
                                logTofile(_eLogPtah, "after");

                                //    return uiAutomationWindow;
                                if (uiAutomationWindow != null)
                                {
                                    WindowPattern winpat = (WindowPattern)uiAutomationWindow.GetCurrentPattern(WindowPattern.Pattern);

                                    try   // This is to handle situations when the window cannot be setfocus
                                    {
                                        winpat.SetWindowVisualState(WindowVisualState.Maximized);
                                        uiAutomationWindow.SetFocus();
                                    }
                                    catch (Exception ex)
                                    {
                                        logTofile(_eLogPtah, "[GetUIAutomationWindow]: Focus could not be set adue to  " + ex.Message.ToString());
                                    }
                                }
                                break;
                            } // end of title case
                        case "titlewildcard":
                            { //start of case titlewildcard
                                logTofile(_eLogPtah, "using  title wildcard  criteria:  " + searchValue);
                                for (var i = 0; i < _Attempts; i++)
                                {
                                    System.Threading.Thread.Sleep(1);
                                    logTofile(_eLogPtah, "Searched for " + i.ToString() + " times");

                                    uiAutomationWindow = GetWindowByPartialName(searchValue);

                                    if (uiAutomationWindow != null)
                                    {
                                        break;
                                    }
                                }
                                if (uiAutomationWindow != null)
                                {
                                    logTofile(_eLogPtah, "window : " + uiAutomationWindow.Current.Name.ToString());
                                }
                                else
                                {
                                    logTofile(_eLogPtah, "Window with Title wildcard : " + searchValue + "was not found");
                                }
                                if (UseWhite == true)
                                {
                                    //wpfapp._application = _application;
                                    //try
                                    //{
                                    //    _globalWindow = wpfapp.GetWPFWindow(searchValue.Trim());
                                    //}
                                    //catch (Exception e)
                                    //{
                                    //    logTofile(_eLogPtah, "exception in getwpfwidow was :" + e.Message);
                                    //}
                                }
                                else
                                {
                                    //logTofile(_eLogPtah, "White window not initialized");
                                }
                                logTofile(_eLogPtah, "after");

                                //    return uiAutomationWindow;
                                if (uiAutomationWindow != null)
                                {
                                    WindowPattern winpat = (WindowPattern)uiAutomationWindow.GetCurrentPattern(WindowPattern.Pattern);

                                    try   // This is to handle situations when the window cannot be setfocus
                                    {
                                        winpat.SetWindowVisualState(WindowVisualState.Maximized);
                                        uiAutomationWindow.SetFocus();
                                    }
                                    catch (Exception ex)
                                    {
                                        logTofile(_eLogPtah, "[GetUIAutomationWindow]: Focus could not be set adue to  " + ex.Message.ToString());
                                    }
                                }
                                break;
                            } // end of titlewildcard case
                        case "titleexact":
                            {

                                logTofile(_eLogPtah, "using  title exact  criteria:  " + searchValue);

                                for (var i = 0; i < _Attempts; i++)
                                {
                                    System.Threading.Thread.Sleep(1);
                                    logTofile(_eLogPtah, "Searched for " + i.ToString() + " times");

                                    uiAutomationWindow = GetWindowByName(searchValue);

                                    if (uiAutomationWindow != null)
                                    {

                                        break;
                                    }
                                }
                                if (uiAutomationWindow != null)
                                {
                                    logTofile(_eLogPtah, "window : " + uiAutomationWindow.Current.Name.ToString());
                                }
                                else
                                {
                                    logTofile(_eLogPtah, "Window with Exact : " + searchValue + "was not found");
                                }
                                if (UseWhite == true)
                                {
                                    /*  wpfapp._application = _application;
                                      try
                                      {
                                          _globalWindow = wpfapp.GetWPFWindow(searchValue.Trim());
                                      }
                                      catch (Exception e)
                                      {
                                          logTofile(_eLogPtah, "exception in getwpfwidow was :" + e.Message);
                                      } */
                                }
                                else
                                {
                                    logTofile(_eLogPtah, "White window not initialized as option is disabled");
                                }

                                if (uiAutomationWindow != null)
                                {
                                    WindowPattern winpat = (WindowPattern)uiAutomationWindow.GetCurrentPattern(WindowPattern.Pattern);

                                    try   // This is to handle situations when the window cannot be setfocus
                                    {
                                        winpat.SetWindowVisualState(WindowVisualState.Maximized);
                                        uiAutomationWindow.SetFocus();
                                    }
                                    catch (Exception ex)
                                    {
                                        logTofile(_eLogPtah, "[GetUIAutomationWindow]: Focus could not be set adue to  " + ex.Message.ToString());
                                    }
                                }
                                break;
                            }

                        case "automationid":
                            {
                                uiAutomationWindow = GetWindowByAutomationId(searchValue);
                                if (UseWhite == true)
                                {
                                    /* wpfapp._application = _application;
                                     try
                                     {
                                         _globalWindow = wpfapp.GetWPFWindow(searchValue.Trim());
                                     }
                                     catch (Exception e)
                                     {
                                         logTofile(_eLogPtah, "exception in getwpfwidow was :" + e.Message);
                                     } */
                                }
                                else
                                {
                                    // logTofile(_eLogPtah, "White window not initialized");
                                }
                                WindowPattern winpat = (WindowPattern)uiAutomationWindow.GetCurrentPattern(WindowPattern.Pattern);
                                try   // This is to handle situations when the window cannot be setfocus
                                {
                                    winpat.SetWindowVisualState(WindowVisualState.Maximized);
                                    uiAutomationWindow.SetFocus();
                                }
                                catch (Exception ex)
                                {
                                    logTofile(_eLogPtah, "[GetUIAutomationWindow]: Focus could not be set adue to  " + ex.Message.ToString());
                                }
                            } // end of automation id case
                            break;
                    } //Switch end
                    uiAutomationCurrentParent = uiAutomationWindow;
                    return uiAutomationWindow;

                } //end of try

                            //   logTofile(_eLogPtah, System.DateTime.Now.ToString() + "Waiting for window" + Environment.NewLine);
                catch (Exception ex)
                {
                    logTofile(_eLogPtah, "Fucntion GetUIAutomationWindow: exeption encoutered");
                    throw new Exception(_error + "UIAutoamtionWindow:" + System.Environment.NewLine + ex.Message);

                }
            } //end of try catch
            else
            {
                uiAutomationCurrentParent = uiAutomationWindow;
                return uiAutomationWindow;
            }
        }
예제 #14
0
        static void Main_2()
        {
            bool isOpened = false;

            try
            {
                //Initializing mandatory parameters for application
                ConfigLibrary.Initialize();

                SystemLog.LogAuditMessage(MethodBase.GetCurrentMethod().Name, DiagnosticLevel.level1, EntityGlobal.ROBO_START, typeof(MainframeAutomation).Name);

                Initialize();

                //isOpened = MainFrameAdapter.OpenPcomSessionAndConnect();
                //Process p = Process.GetProcesses().SingleOrDefault(item => item.ProcessName == "pcsws");
//                Process.GetProcessById("")
                Process p = Process.GetProcesses().SingleOrDefault(item => item.ProcessName == "filezilla");
                System.Windows.Automation.AutomationElement t = WinFormAdapter.GetAEFromHandle(p.MainWindowHandle);

                //System.Windows.Automation.ControlType
                System.Windows.Automation.AutomationElement fdsfasdf = WinFormAdapter.GetAEOnChildByName(t, "ID_QUICKCONNECTBAR");
                //System.Windows.Automation.AutomationElement fdsfasdf = WinFormAdapter.GetAEOnChildByName(t, "Servidor:");

                WinFormAdapter.SetTextInTextArea(t, "fdsafsafasfdasfdsafdasfasfasdfasdfdsafsdafdasfdasfasd " + "\r\n" + "gfsdfdafs" + "\t" + "gadsfdad");
                WinFormAdapter.SetTextInTextArea(t, "servidor" + "\t" + "usuario" + "\t" + "contraseña");

                /*System.Windows.Automation.AutomationElement Servidor = WinFormAdapter.GetAEOnChildById(fdsfasdf, "-31800");
                *  System.Windows.Automation.AutomationElement Servidor1 = WinFormAdapter.GetAEOnChildById(fdsfasdf, "31801");*/
                System.Windows.Automation.AutomationElement Servidor       = WinFormAdapter.GetAEOnChildByName(fdsfasdf, ControlType.Edit, "Servidor:");
                System.Windows.Automation.AutomationElement conexionRapida = WinFormAdapter.GetAEOnChildById(fdsfasdf, "-31925");
                //System.Windows.Automation.AutomationElement conexionRapida = WinFormAdapter.GetAEOnChildByName(fdsfasdf, "Conexión rápida");
                WinFormAdapter.SetText(Servidor, "hola");

                //Point conexionRapida.GetClickablePoint();

                WinFormAdapter.ClickElement(conexionRapida);

                //WinFormAdapter.SetText(WinFormAdapter.GetAEOnChildByName(fdsfasdf, "Conexión rápida"), "rrorro");

                //System.Windows.Automation.AutomationElement t2 = WinFormAdapter.GetDialogBox("");

                t.SetFocus();
                //WinFormAdapter.SetText(t, "eeee");
                WinFormAdapter.SetTextInTextArea(t, "fdsafsafasfdasfdsafdasfasfasdfasdfdsafsdafdasfdasfasd " + "\r\n" + "gfsdfdafs" + "\t" + "gadsfdad");
                string texto = WinFormAdapter.GetText(t); //>> devuelve:  //Microsoft Excel - Libro1

                t.GetRuntimeId();
                t.SetFocus();
                System.Windows.Point punto = new System.Windows.Point(40, 40);


                System.Windows.Automation.AutomationElement xx = WinFormAdapter.GetAEFromBoundingRectangle(punto);


                string www = WinFormAdapter.GetText(xx);
                //WinFormAdapter.SetTextInTextArea(xx, "EFDSFSDAFSFDSAFASFA");
                IntPtr e = WinFormAdapter.GetHandleForAE(t);

                const uint WM_KEYDOWN      = 0x100;
                const uint KEYEVENTF_KEYUP = 0x0002;
                /*IntPtr result3 = SendMessage(WindowToFind, WM_KEYDOWN, ((IntPtr)k), (IntPtr)0);*/
                SendMessage(e, WM_KEYDOWN, (IntPtr)Keys.Enter, (IntPtr)0);

                WinFormAdapter.SetWindowForeground(e);
                bool eeee = SetForegroundWindow(e);
                keybd_event((byte)((char)Keys.Enter), 0, KEYEVENTF_KEYUP, IntPtr.Zero);
                keybd_event((byte)((char)Keys.Enter), 0, KEYEVENTF_KEYUP, IntPtr.Zero);
                keybd_event((byte)((char)Keys.Enter), 0, KEYEVENTF_KEYUP, IntPtr.Zero);
                keybd_event((byte)((char)Keys.A), 0, KEYEVENTF_KEYUP, IntPtr.Zero);
                keybd_event((byte)((char)Keys.A), 0, KEYEVENTF_KEYUP, IntPtr.Zero);
                keybd_event((byte)((char)Keys.A), 0, KEYEVENTF_KEYUP, IntPtr.Zero);
                keybd_event((byte)((char)Keys.A), 0, KEYEVENTF_KEYUP, IntPtr.Zero);
                keybd_event((byte)((char)Keys.A), 0, KEYEVENTF_KEYUP, IntPtr.Zero);
                keybd_event((byte)((char)Keys.Enter), 0, KEYEVENTF_KEYUP, IntPtr.Zero);
                keybd_event((byte)((char)Keys.Enter), 0, KEYEVENTF_KEYUP, IntPtr.Zero);

                //SendKeys.SendWait("EE");
                //SendKeys.SendWait(Keys.Enter.ToString());

                /*SendKeys.Send("K");
                 * SendKeys.Send(Keys.Enter.ToString());
                 * SendKeys.Send(Keys.Enter.ToString());
                 * SendKeys.Send(Keys.Enter.ToString());
                 * SendKeys.Send(Keys.Enter.ToString());
                 * SendKeys.Send(Keys.Enter.ToString());
                 * SendKeys.Send(Keys.Enter.ToString());*/



                Console.Write(www);
                MessageBox.Show(www);

                //System.Windows.Automation.AutomationElement t3 = WinFormAdapter.GetAEOnChildByName(t, "");


                //WinFormAdapter.ClickElement(t2);

                /*System.Windows.Automation.AutomationElement t3 = WinFormAdapter.GetAE()
                 *
                 * WinFormAdapter.SetText(t2, "BFPJUARUI");*/
                //Thread.Sleep(1000000);

                /*if (isOpened)
                 * {
                 *  new BusinessLogic.BLIspfValidator().DoActivities();
                 * }**/
                Thread.Sleep(10000900);
            }
            catch (TcsRpaException e)
            {
                SystemLog.LogErrorMessage(e, typeof(MainframeAutomation).Name, MethodBase.GetCurrentMethod().Name);
            }
            catch (Exception e)
            {
                SystemLog.LogErrorMessage(e, typeof(MainframeAutomation).Name, MethodBase.GetCurrentMethod().Name);
            }
            finally
            {
                if (isOpened)
                {
                    MainFrameAdapter.ClosePCOM();
                }
            }

            SystemLog.LogAuditMessage(MethodBase.GetCurrentMethod().Name, DiagnosticLevel.level1, EntityGlobal.ROBO_END, typeof(MainframeAutomation).Name);
            Thread.Sleep(2000);
        }
예제 #15
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;
            }
        }
예제 #16
0
        /// --------------------------------------------------------------------
        /// <summary>
        ///     Inserts a string into each text control of interest.
        /// </summary>
        /// <param name="element">A text control.</param>
        /// <param name="value">The string to be inserted.</param>
        /// --------------------------------------------------------------------
        private void InsertTextUsingUiAutomation(AutomationElement element,
            string value)
        {
            try
            {
                // Validate arguments / initial setup
                if (value == null)
                    throw new ArgumentNullException(
                        "String parameter must not be null.");

                if (element == null)
                    throw new ArgumentNullException(
                        "AutomationElement parameter must not be null");

                // A series of basic checks prior to attempting an insertion.
                //
                // Check #1: Is control enabled?
                // An alternative to testing for static or read-only controls 
                // is to filter using 
                // PropertyCondition(AutomationElement.IsEnabledProperty, true) 
                // and exclude all read-only text controls from the collection.
                if (!element.Current.IsEnabled)
                {
                    throw new InvalidOperationException(
                        "The control with an AutomationID of "
                        + element.Current.AutomationId
                        + " is not enabled.\n\n");
                }

                // Check #2: Are there styles that prohibit us 
                //           from sending text to this control?
                if (!element.Current.IsKeyboardFocusable)
                {
                    throw new InvalidOperationException(
                        "The control with an AutomationID of "
                        + element.Current.AutomationId
                        + "is read-only.\n\n");
                }


                // Once you have an instance of an AutomationElement,  
                // check if it supports the ValuePattern pattern.
                object valuePattern = null;

                // Control does not support the ValuePattern pattern 
                // so use keyboard input to insert content.
                //
                // NOTE: Elements that support TextPattern 
                //       do not support ValuePattern and TextPattern
                //       does not support setting the text of 
                //       multi-line edit or document controls.
                //       For this reason, text input must be simulated
                //       using one of the following methods.
                //       
                if (!element.TryGetCurrentPattern(
                    ValuePattern.Pattern, out valuePattern))
                {
                    _feedbackText.Append("The control with an AutomationID of ")
                        .Append(element.Current.AutomationId)
                        .Append(" does not support ValuePattern.")
                        .AppendLine(" Using keyboard input.\n");

                    // Set focus for input functionality and begin.
                    element.SetFocus();

                    // Pause before sending keyboard input.
                    Thread.Sleep(100);

                    // Delete existing content in the control and insert new content.
                    SendKeys.SendWait("^{HOME}"); // Move to start of control
                    SendKeys.SendWait("^+{END}"); // Select everything
                    SendKeys.SendWait("{DEL}"); // Delete selection
                    SendKeys.SendWait(value);
                }
                // Control supports the ValuePattern pattern so we can 
                // use the SetValue method to insert content.
                else
                {
                    _feedbackText.Append("The control with an AutomationID of ")
                        .Append(element.Current.AutomationId)
                        .Append((" supports ValuePattern."))
                        .AppendLine(" Using ValuePattern.SetValue().\n");

                    // Set focus for input functionality and begin.
                    element.SetFocus();

                    ((ValuePattern) valuePattern).SetValue(value);
                }
            }
            catch (ArgumentNullException exc)
            {
                _feedbackText.Append(exc.Message);
            }
            catch (InvalidOperationException exc)
            {
                _feedbackText.Append(exc.Message);
            }
            finally
            {
                Feedback(_feedbackText.ToString());
            }
        }
예제 #17
0
 public static void AutomationElementSetFocus(AutomationElement element)
 {
     Dump("SetFocus()", true, element);
     try
     {
         element.SetFocus();
     }
     catch (Exception exception)
     {
         VerifyException(element, exception,
             typeof(ElementNotAvailableException),
             typeof(ElementNotEnabledException),
             typeof(InvalidOperationException) /* {"The target element could not receive focus."}*/
             );
             
     }
 }
예제 #18
0
파일: UITree.cs 프로젝트: OVRLab/SeleniumPP
 public bool SetFocus(AutomationElement elm)
 {
     elm.SetFocus();
     return true;
 }