søndag 29. mai 2011

Microsoft UI Automation

A colleague of mine (from earlier) once asked me what the operator ++ did. YES, it was VERY funny and we all laughed. The reason it was funny was that he had been programming for several years. He had been using variable = variable + 1 instead.
With this in mind I looked at the System.Windows.Automation namespace in .Net framework 4.0. This is the Microsoft UI Automation library which is great to use when automating testing of the user interface.

I created a library that could put away the use of ++ :), by using.... calc.exe (calculator in windows) !!! The program itself is very simple, but the main purpose was to use Microsoft UI Automation, and it works great. Here is the code:

        private int AddOne(int number)
        {
            using (var p = Process.Start("calc.exe"))
            {
                //allow time to startup
                System.Threading.Thread.Sleep(500);
                var calcWindow = AutomationElement.FromHandle(p.MainWindowHandle);

                foreach (char c in number.ToString())
                {
                    PushButton(calcWindow, c.ToString());
                }

                PushButton(calcWindow, "Add");
                PushButton(calcWindow, "1");
                PushButton(calcWindow, "Equals");

                int result = GetResult(calcWindow);
                p.Kill();
                return result;
            }
        }

        private int GetResult(AutomationElement window)
        {
            var controls = window.FindAll(TreeScope.Descendants, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Text));

            foreach (AutomationElement control in controls)
            {
                int result;
                if (int.TryParse(control.Current.Name,out result))
                    return result;
            }

            return 0;
        }

        private AutomationElement GetButton(AutomationElement searchIn, string searchFor)
        {
            var buttons = searchIn.FindAll(TreeScope.Descendants, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Button));

            foreach (AutomationElement button in buttons)
            {
                if (button.Current.Name == searchFor)
                    return button;
            }

            return null;
        }

        private void PushButton(AutomationElement window, string buttonName)
        {
            var button = GetButton(window, buttonName);
            if (button != null)
                (button.GetCurrentPattern(InvokePattern.Pattern) as InvokePattern).Invoke();
        }
    }

Ingen kommentarer:

Legg inn en kommentar