public void GetMatches_ReturnsThreeMatchLocations_When666IsMatchedAgainst()
        {
            string matchTarget = "666";
            TextPattern pattern = new TextPattern(dummyRegexPattern);

            Assert.Equal(pattern.GetMatches(matchTarget).Count(), 3);
        }
Example #2
0
 internal TextPatternRange(UIAutomationClient.IUIAutomationTextRange range, TextPattern pattern)
 {
     Debug.Assert(range != null);
     Debug.Assert(pattern != null);
     this._range = range;
     this._pattern = pattern;
 }
Example #3
0
 internal static TextPatternRange Wrap(SafeTextRangeHandle hTextRange, TextPattern pattern)
 {
     if (hTextRange.IsInvalid)
     {
         return null;
     }
     return new TextPatternRange(hTextRange, pattern);
 }
Example #4
0
        //------------------------------------------------------
        //
        //  Constructors
        //
        //------------------------------------------------------

        #region Constructors

        internal TextPatternRange(SafeTextRangeHandle hTextRange, TextPattern pattern)
        {
            Debug.Assert(!hTextRange.IsInvalid);
            Debug.Assert(pattern != null);

            _hTextRange = hTextRange;
            _pattern = pattern;
        }
Example #5
0
 internal static TextPatternRange Wrap(UIAutomationClient.IUIAutomationTextRange range, TextPattern pattern)
 {
     Debug.Assert(pattern != null);
     if (range == null)
     {
         return null;
     }
     else
     {
         return new TextPatternRange(range, pattern);
     }
 }
Example #6
0
        public string GetSelectedText()
        {
            AutomationElement ae = AutomationElement.FocusedElement;

            TextPattern tp = ae.GetCurrentPattern(TextPattern.Pattern) as TextPattern;

            if (tp == null)
            {
                return("");
            }

            TextPatternRange[] trs;

            if (tp.SupportedTextSelection == SupportedTextSelection.None)
            {
                return("");
            }
            else
            {
                trs = tp.GetSelection();
                return(trs[0].GetText(-1));
            }
        }
Example #7
0
        public void MoveEndpointByCharacter()
        {
            SetText("The quick\tbrown (fox] \"jumps\"\rover:\nthe  lazy, dog.");
            Thread.Sleep(500);

            TextPattern      textPattern = (TextPattern)textbox3Element.GetCurrentPattern(TextPattern.Pattern);
            TextPatternRange range       = textPattern.DocumentRange.Clone();

            int moved_units = range.MoveEndpointByUnit(TextPatternRangeEndpoint.Start, TextUnit.Character, 0);

            Assert.AreEqual(0, moved_units);
            Assert.AreEqual("The quick\tbrown (fox] \"jumps\"\rover:\nthe  lazy, dog.", range.GetText(-1));

            moved_units = range.MoveEndpointByUnit(TextPatternRangeEndpoint.Start, TextUnit.Character, 1);
            Assert.AreEqual(1, moved_units);
            Assert.AreEqual("he quick\tbrown (fox] \"jumps\"\rover:\nthe  lazy, dog.", range.GetText(-1));

            moved_units = range.MoveEndpointByUnit(TextPatternRangeEndpoint.Start, TextUnit.Character, 8);
            Assert.AreEqual(8, moved_units);
            Assert.AreEqual("\tbrown (fox] \"jumps\"\rover:\nthe  lazy, dog.", range.GetText(-1));

            moved_units = range.MoveEndpointByUnit(TextPatternRangeEndpoint.Start, TextUnit.Character, 1000);
            Assert.AreEqual(42, moved_units);
            Assert.AreEqual(String.Empty, range.GetText(-1));

            moved_units = range.MoveEndpointByUnit(TextPatternRangeEndpoint.Start, TextUnit.Character, -1000);
            Assert.AreEqual(-52, moved_units);
            Assert.AreEqual("The quick\tbrown (fox] \"jumps\"\rover:\nthe  lazy, dog.", range.GetText(-1));

            moved_units = range.MoveEndpointByUnit(TextPatternRangeEndpoint.Start, TextUnit.Character, 5);
            Assert.AreEqual(5, moved_units);
            Assert.AreEqual("uick\tbrown (fox] \"jumps\"\rover:\nthe  lazy, dog.", range.GetText(-1));

            moved_units = range.MoveEndpointByUnit(TextPatternRangeEndpoint.Start, TextUnit.Character, -3);
            Assert.AreEqual(-3, moved_units);
            Assert.AreEqual("e quick\tbrown (fox] \"jumps\"\rover:\nthe  lazy, dog.", range.GetText(-1));
        }
Example #8
0
        public void VerifyInput()
        {
            AutomationElement rootElement;
            Process           appProcess = AutomationHelpers.StartProcess(new ProcessStartInfo("SampleApp.exe"), out rootElement);

            AutomationElement inputTextBox  = AutomationUtilities.FindElementsById(rootElement, "inputTextBox")[0];
            AutomationElement outputTextBox = AutomationUtilities.FindElementsById(rootElement, "outputTextBox")[0];
            AutomationElement button        = AutomationUtilities.FindElementsById(rootElement, "appendButton")[0];

            string inputText    = "TestTest";
            string expectedText = inputText + "\n";

            WindowPattern winPattern = (WindowPattern)rootElement.GetCurrentPattern(WindowPatternIdentifiers.Pattern);

            AutomationHelpers.MoveToAndClick(inputTextBox);
            winPattern.WaitForInputIdle(1000);
            Microsoft.Test.Keyboard.Type(inputText);
            winPattern.WaitForInputIdle(1000);
            AutomationHelpers.MoveToAndClick(button);
            winPattern.WaitForInputIdle(1000);

            object o;

            outputTextBox.TryGetCurrentPattern(TextPatternIdentifiers.Pattern, out o);
            TextPattern pattern    = (TextPattern)o;
            string      actualText = pattern.DocumentRange.GetText(-1);

            try
            {
                Assert.AreEqual(expectedText, actualText, "The text did not match. Expected: {0}  Actual: {1}", expectedText, actualText);
            }
            finally
            {
                AutomationHelpers.CloseWindow(rootElement);
                appProcess.WaitForExit();
            }
        }
        [TestProperty("Ignore", "True")] // GH#7282 - investigate and reenable
        public void CanExpandToEnclosingUnitTextRangeProvider()
        {
            using (CmdApp app = new CmdApp(CreateType.ProcessOnly, TestContext))
            {
                var sbiex = app.GetScreenBufferInfo();
                sbiex.dwSize.Y = (short)(2 * sbiex.srWindow.Height);
                app.SetScreenBufferInfo(sbiex);

                AutomationElement  textAreaUiaElement = GetTextAreaUiaElement(app);
                TextPattern        textPattern        = textAreaUiaElement.GetCurrentPattern(TextPattern.Pattern) as TextPattern;
                TextPatternRange[] visibleRanges      = textPattern.GetVisibleRanges();
                TextPatternRange   testRange          = visibleRanges.First().Clone();

                // change testRange to a degenerate range and then expand to a line
                testRange.MoveEndpointByRange(TextPatternRangeEndpoint.End, testRange, TextPatternRangeEndpoint.Start);
                Verify.AreEqual(0, testRange.CompareEndpoints(TextPatternRangeEndpoint.Start,
                                                              testRange,
                                                              TextPatternRangeEndpoint.End));
                testRange.ExpandToEnclosingUnit(TextUnit.Line);
                Verify.IsTrue(testRange.Compare(visibleRanges[0]));

                // expand to document size
                testRange.ExpandToEnclosingUnit(TextUnit.Document);
                Verify.IsTrue(testRange.Compare(textPattern.DocumentRange));

                // shrink back to a line
                testRange.ExpandToEnclosingUnit(TextUnit.Line);
                Verify.IsTrue(testRange.Compare(visibleRanges[0]));

                // make the text buffer start to cycle its buffer
                _FillOutputBufferWithData(app);

                // expand to document range again
                testRange.ExpandToEnclosingUnit(TextUnit.Document);
                Verify.IsTrue(testRange.Compare(textPattern.DocumentRange));
            }
        }
Example #10
0
        public void Select(string ItemName)
        {
            this.Open();
            int itemindex = -1;

            if (ItemName.IndexOf('#') == 0)
            {
                itemindex = Convert.ToInt16(ItemName.Substring(1));
            }
            Condition listCondtion               = new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.ListItem);
            AutomationElementCollection ac       = this._condition.AutomationElement.FindAll(TreeScope.Descendants, listCondtion);
            AutomationElement           listitem = null;

            if (itemindex != -1)
            {
                if (ac.Count - 1 < itemindex)
                {
                    ControlSearcher.ThrowError(ErrorType.OutRange);
                }
                else
                {
                    listitem = ac[itemindex];
                }
            }
            else
            {
                for (int i = 0; i < ac.Count; i++)
                {
                    if (ac[i].Current.Name.Trim() == ItemName.Trim())
                    {
                        listitem = ac[i];
                    }
                }
                if (listitem == null)
                {
                    for (int i = 0; i < ac.Count; i++)
                    {
                        TextPattern t = (TextPattern)ac[i].GetCurrentPattern(TextPattern.Pattern);
                        if (t.DocumentRange.GetText(-1).Trim() == ItemName.Trim())
                        {
                            listitem = ac[i];
                        }
                    }
                }

                if (listitem == null)
                {
                    for (int i = 0; i < ac.Count; i++)
                    {
                        ValuePattern v = (ValuePattern)ac[i].GetCurrentPattern(ValuePattern.Pattern);
                        if (v.Current.Value.Trim() == ItemName.Trim())
                        {
                            listitem = ac[i];
                        }
                    }
                }
            }

            if (listitem != null)
            {
                try
                {
                    SelectionItemPattern itempattern = (SelectionItemPattern)listitem.GetCurrentPattern(SelectionItemPattern.Pattern);
                    itempattern.Select();
                    if (_checkvalue(listitem.Current.Name))
                    {
                        return;
                    }
                }
                catch
                {
                }

                try
                {
                    if (listitem.Current.NativeWindowHandle != 0)
                    {
                        KeyInput.Click(KeyInput.MouseClickType.LClick, listitem.Current.NativeWindowHandle);
                        if (_checkvalue(listitem.Current.Name))
                        {
                            return;
                        }
                    }
                }
                catch
                { }

                try
                {
                    Point p = new Point((int)listitem.Current.BoundingRectangle.Left, (int)listitem.Current.BoundingRectangle.Top);
                    KeyInput.Click(KeyInput.MouseClickType.LClick, p);
                    if (_checkvalue(listitem.Current.Name))
                    {
                        return;
                    }
                }
                catch
                { }
                //ControlSearcher.ThrowError(ErrorType.CannotperforthisOperation);
            }
            else
            {
                ControlSearcher.ThrowError(ErrorType.NotItemExistinthelist);
            }
        }
        /// <summary>
        /// Finds the desired text within the whole document text.
        /// </summary>
        /// <param name="control">The UI Automation element</param>
        /// <param name="find">The string to find.</param>
        /// <param name="searchBackward">if set to <c>true</c> search backward from the end of the document.</param>
        /// <param name="ignoreCase">if set to <c>true</c> ignore case.</param>
        /// <returns>
        /// A text range matching the specified text; otherwise null
        /// </returns>
        internal static TextPatternRange FindText(AutomationElement control, string find, bool searchBackward, bool ignoreCase)
        {
            TextPattern pat = (TextPattern)CommonUIAPatternHelpers.CheckPatternSupport(TextPattern.Pattern, control);

            return(pat.DocumentRange.FindText(find, searchBackward, ignoreCase));
        }
Example #12
0
 internal static TextPatternRange[] Wrap(UIAutomationClient.IUIAutomationTextRangeArray ranges, TextPattern pattern)
 {
     if (ranges == null)
     {
         return(null);
     }
     TextPatternRange[] rangeArray = new TextPatternRange[ranges.Length];
     for (int i = 0; i < ranges.Length; i++)
     {
         rangeArray[i] = new TextPatternRange(ranges.GetElement(i), pattern);
     }
     return(rangeArray);
 }
Example #13
0
        public void GetMatches_ReturnsOneMatchLocation_WhenIdenticalStringIsMatchedAgainst()
        {
            TextPattern pattern = new TextPattern(dummyString);

            Assert.Equal(pattern.GetMatches(dummyString).Count(), 1);
        }
Example #14
0
        [TestProperty("Ignore", "True")] // GH#7282 - investigate and reenable
        public void CanMoveEndpointByUnitNearBottomBoundary()
        {
            using (CmdApp app = new CmdApp(CreateType.ProcessOnly, TestContext))
            {
                var sbiex = app.GetScreenBufferInfo();
                sbiex.dwSize.Y = (short)(2 * sbiex.srWindow.Height);
                app.SetScreenBufferInfo(sbiex);

                AutomationElement  textAreaUiaElement = GetTextAreaUiaElement(app);
                TextPattern        textPattern        = textAreaUiaElement.GetCurrentPattern(TextPattern.Pattern) as TextPattern;
                TextPatternRange[] visibleRanges      = textPattern.GetVisibleRanges();
                TextPatternRange   testRange          = visibleRanges.First().Clone();

                // assumes that range is a line range at the bottom of the screen buffer
                Action <TextPatternRange> testBottomBoundary = delegate(TextPatternRange range)
                {
                    // the range is at the bottom of the screen buffer, we
                    // shouldn't be able to move the endpoint endpoint down
                    int moveAmount = range.MoveEndpointByUnit(TextPatternRangeEndpoint.End, TextUnit.Line, 1);
                    Verify.AreEqual(0, moveAmount);

                    // we shouldn't be able to move the starting endpoint down either
                    moveAmount = range.MoveEndpointByUnit(TextPatternRangeEndpoint.Start, TextUnit.Line, 1);
                    Verify.AreEqual(0, moveAmount);
                };

                // move the range to the bottom of the screen
                int rowsToMove = _GetTotalRows(app) - 1;
                int moveCount  = testRange.Move(TextUnit.Line, rowsToMove);
                Verify.AreEqual(rowsToMove, moveCount);

                testBottomBoundary(testRange);

                // we want to test that the boundaries are still observed
                // when the screen buffer index and text buffer index don't align.
                // write a bunch of text to the screen to fill up the text
                // buffer and make it start to reuse its buffer
                _FillOutputBufferWithData(app);
                Globals.WaitForTimeout();

                // move all the way to the top
                visibleRanges = textPattern.GetVisibleRanges();
                testRange     = visibleRanges.First().Clone();
                while (true)
                {
                    int moved = testRange.Move(TextUnit.Line, -1);
                    if (moved == 0)
                    {
                        break;
                    }
                }

                // we're at the top of the screen buffer, so move back to the bottom
                // so we can test
                rowsToMove = _GetTotalRows(app) - 1;
                moveCount  = testRange.Move(TextUnit.Line, rowsToMove);
                Verify.AreEqual(rowsToMove, moveCount);
                testRange.ScrollIntoView(true);

                testBottomBoundary(testRange);
            }
        }
Example #15
0
    public void VerifyInput()
    {
        //
        // Start the application we are testing
        //
        string sampleAppPath   = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase), "SampleApp.exe");
        AutomatedApplication a = new OutOfProcessApplication(new OutOfProcessApplicationSettings
        {
            ProcessStartInfo = new ProcessStartInfo(sampleAppPath),
            ApplicationImplementationFactory = new UIAutomationOutOfProcessApplicationFactory()
        });

        a.Start();

        try
        {
            a.WaitForMainWindow(TimeSpan.FromSeconds(10));
            var mainWindow = a.MainWindow as AutomationElement;

            //
            // Discover various elements in the UI
            //
            AutomationElement inputTextBox  = AutomationUtilities.FindElementsById(mainWindow, "inputTextBox")[0];
            AutomationElement outputTextBox = AutomationUtilities.FindElementsById(mainWindow, "outputTextBox")[0];
            AutomationElement appendButton  = AutomationUtilities.FindElementsById(mainWindow, "appendButton")[0];

            //
            // Click on the input text box and simulate typing
            //
            string inputText    = "TestTest";
            string expectedText = inputText + "\n";

            WindowPattern winPattern = mainWindow.GetCurrentPattern(WindowPattern.Pattern) as WindowPattern;
            Helpers.MoveToAndClick(inputTextBox);
            winPattern.WaitForInputIdle(1000);
            Microsoft.Test.Input.Keyboard.Type(inputText);
            winPattern.WaitForInputIdle(1000);

            //
            // Now click the button
            //
            Helpers.MoveToAndClick(appendButton);
            winPattern.WaitForInputIdle(1000);

            //
            // Now, get the text of the outputTextBox and compare it against what's expected
            // Fail the test if expected != actual
            //
            TextPattern textPattern = outputTextBox.GetCurrentPattern(TextPattern.Pattern) as TextPattern;
            string      actualText  = textPattern.DocumentRange.GetText(-1);

            //
            // Report the test result
            //
            Assert.AreEqual(expectedText, actualText);
        }
        finally
        {
            //
            // Close the tested application
            //
            a.Close();
        }
    }
        public void CanMoveRange()
        {
            using (CmdApp app = new CmdApp(CreateType.ProcessOnly, TestContext))
            {
                AutomationElement  textAreaUiaElement = GetTextAreaUiaElement(app);
                TextPattern        textPattern        = textAreaUiaElement.GetCurrentPattern(TextPattern.Pattern) as TextPattern;
                TextPatternRange[] visibleRanges      = textPattern.GetVisibleRanges();
                TextPatternRange   testRange          = visibleRanges.First().Clone();


                // assumes range is at the top of the screen buffer
                Action <TextPatternRange> testMovement = delegate(TextPatternRange range)
                {
                    // the range is at the top of the screen
                    // buffer, we shouldn't be able to move up.
                    int moveAmount = range.Move(TextUnit.Line, -1);
                    Verify.AreEqual(0, moveAmount);

                    // move to the bottom of the screen
                    // - 1 because we're already on the 0th row
                    int rowsToMove = _GetTotalRows(app) - 1;
                    moveAmount = range.Move(TextUnit.Line, rowsToMove);
                    Verify.AreEqual(rowsToMove, moveAmount);

                    // try to move one more row down, we should not be able to
                    moveAmount = range.Move(TextUnit.Line, 1);
                    Verify.AreEqual(0, moveAmount);

                    // move the range up to the top again, one row at a time,
                    // making sure that we have only one line being encompassed
                    // by the range. We check this by counting the number of
                    // bounding rectangles that represent the range.
                    for (int i = 0; i < rowsToMove; ++i)
                    {
                        moveAmount = range.Move(TextUnit.Line, -1);
                        // we need to scroll into view or getting the boundary
                        // rectangles might return 0
                        Verify.AreEqual(-1, moveAmount);
                        range.ScrollIntoView(true);
                        Rect[] boundingRects = range.GetBoundingRectangles();
                        Verify.AreEqual(1, boundingRects.GetLength(0));
                    }

                    // and back down to the bottom, one row at a time
                    for (int i = 0; i < rowsToMove; ++i)
                    {
                        moveAmount = range.Move(TextUnit.Line, 1);
                        // we need to scroll into view or getting the boundary
                        // rectangles might return 0
                        Verify.AreEqual(1, moveAmount);
                        range.ScrollIntoView(true);
                        Rect[] boundingRects = range.GetBoundingRectangles();
                        Verify.AreEqual(1, boundingRects.GetLength(0));
                    }
                };

                testMovement(testRange);

                // test again with unaligned text buffer and screen buffer
                _FillOutputBufferWithData(app);
                Globals.WaitForTimeout();

                visibleRanges = textPattern.GetVisibleRanges();
                testRange     = visibleRanges.First().Clone();
                // move range back to the top
                while (true)
                {
                    int moveCount = testRange.Move(TextUnit.Line, -1);
                    if (moveCount == 0)
                    {
                        break;
                    }
                }

                testMovement(testRange);
            }
        }
Example #17
0
 /// <summary>
 /// Exposes methods and properties used in batch styling of text.  In contrast to the TextAnnotator
 /// class, this class is meant to be used in the styling of *formatted* strings, i.e. strings that
 /// follow the "{0}, {1}...{n}" pattern.
 /// </summary>
 /// <param name="defaultColor">
 /// The color to be associated with unstyled text.
 /// </param>
 public TextFormatter(
     Color defaultColor)
 {
     _defaultColor = defaultColor;
     _textPattern  = new TextPattern(_defaultFormatToken);
 }
Example #18
0
        public static void GetValue(AutomationElement element, ref string value)
        {
            TextPattern valuePattern = (TextPattern)element.GetCurrentPattern(TextPattern.Pattern);

            value = valuePattern.DocumentRange.GetText(-1);
        }
Example #19
0
        public void ParagraphNormalize()
        {
            string text = "gomez thing\r\nmorticia\twednesday";

            SetText(text);
            Thread.Sleep(500);

            TextPattern      textPattern = (TextPattern)textbox3Element.GetCurrentPattern(TextPattern.Pattern);
            TextPatternRange range       = textPattern.DocumentRange.Clone();

            // NOTE: These all pass successfully on Windows Vista, so
            // think twice before you change anything.

            // Case #1
            int moved_units;

            // Looks like gtk collapses \r\n into one char
            moved_units = range.MoveEndpointByUnit(TextPatternRangeEndpoint.End, TextUnit.Character, -100);
            // Seems that SWF treats \n as two chars or something similar
            int expected = (Atspi? -31: -32);

            Assert.AreEqual(expected, moved_units, "Case 1: Moved units are incorrect in -100 character move");
            Assert.AreEqual(String.Empty, range.GetText(-1), "Case 1: Text is incorrect in -100 character move");

            range.ExpandToEnclosingUnit(TextUnit.Paragraph);
            Assert.AreEqual("gomez thing\r\n", range.GetText(-1), "Case 1: Text is incorrect in ExpandToEnclosingUnit");

            // Case #2
            range = textPattern.DocumentRange.Clone();

            moved_units = range.MoveEndpointByUnit(TextPatternRangeEndpoint.End, TextUnit.Character, -23);
            Assert.AreEqual(-23, moved_units, "Case 2: Moved units are incorrect in -23 character move");
            Assert.AreEqual("gomez th", range.GetText(-1), "Case 2: Text is incorrect in -23 character move");

            range.ExpandToEnclosingUnit(TextUnit.Paragraph);
            Assert.AreEqual("gomez thing\r\n", range.GetText(-1), "Case 2: Text is incorrect in ExpandToEnclosingUnit");

            // Case #3
            range = textPattern.DocumentRange.Clone();

            moved_units = range.MoveEndpointByUnit(TextPatternRangeEndpoint.End, TextUnit.Character, -18);
            Assert.AreEqual(-18, moved_units, "Case 3: Moved units are incorrect in -18 character move");
            Assert.AreEqual("gomez thing\r\n", range.GetText(-1), "Case 3: Text is incorrect in -18 character move");

            range.ExpandToEnclosingUnit(TextUnit.Paragraph);
            Assert.AreEqual("gomez thing\r\n", range.GetText(-1), "Case 3: Text is incorrect in ExpandToEnclosingUnit");

            // Case #4
            range = textPattern.DocumentRange.Clone();

            moved_units = range.MoveEndpointByUnit(TextPatternRangeEndpoint.End, TextUnit.Character, -14);
            Assert.AreEqual(-14, moved_units, "Case 4: Moved units are incorrect in -14 character move");
            Assert.AreEqual("gomez thing\r\nmort", range.GetText(-1), "Case 4: Text is incorrect in -14 character move");

            // XXX: Behaves differently than TextUnit.Line
            range.ExpandToEnclosingUnit(TextUnit.Paragraph);
            Assert.AreEqual("gomez thing\r\nmorticia\twednesday", range.GetText(-1), "Case 4: Text is incorrect in ExpandToEnclosingUnit");

            // Case #5
            range = textPattern.DocumentRange.Clone();

            moved_units = range.MoveEndpointByUnit(TextPatternRangeEndpoint.Start, TextUnit.Character, 2);
            Assert.AreEqual(2, moved_units, "Case 5: Moved units are incorrect in +2 character move");
            Assert.AreEqual("mez thing\r\nmorticia\twednesday", range.GetText(-1), "Case 5: Text is incorrect in +2 character move");

            moved_units = range.MoveEndpointByUnit(TextPatternRangeEndpoint.End, TextUnit.Character, -100);
            expected    = (Atspi? -31: -32);
            Assert.AreEqual(expected, moved_units, "Case 1: Moved units are incorrect in -100 character move");
            Assert.AreEqual(String.Empty, range.GetText(-1), "Case 5: Text is incorrect in -100 character move");

            range.ExpandToEnclosingUnit(TextUnit.Paragraph);
            Assert.AreEqual("gomez thing\r\n", range.GetText(-1), "Case 5: Text is incorrect in ExpandToEnclosingUnit");

            // Case #6
            range = textPattern.DocumentRange.Clone();

            moved_units = range.MoveEndpointByUnit(TextPatternRangeEndpoint.End, TextUnit.Character, -18);
            Assert.AreEqual(-18, moved_units, "Case 6: Moved units are incorrect in -18 character move");
            Assert.AreEqual("gomez thing\r\n", range.GetText(-1), "Case 6: Text is incorrect in -18 character move");

            moved_units = range.MoveEndpointByUnit(TextPatternRangeEndpoint.Start, TextUnit.Character, 2);
            Assert.AreEqual(2, moved_units, "Case 6: Moved units are incorrect in +2 character move");
            Assert.AreEqual("mez thing\r\n", range.GetText(-1), "Case 6: Text is incorrect in 2 character move");

            moved_units = range.MoveEndpointByUnit(TextPatternRangeEndpoint.End, TextUnit.Character, -4);
            Assert.AreEqual(-4, moved_units, "Case 6: Moved units are incorrect in -4 character move");
            Assert.AreEqual("mez thi", range.GetText(-1), "Case 6: Text is incorrect in -4 character move");

            range.ExpandToEnclosingUnit(TextUnit.Paragraph);
            Assert.AreEqual("gomez thing\r\n", range.GetText(-1), "Case 6: Text is incorrect in ExpandToEnclosingUnit");

            // Case #7
            range = textPattern.DocumentRange.Clone();

            moved_units = range.MoveEndpointByUnit(TextPatternRangeEndpoint.End, TextUnit.Character, -18);
            Assert.AreEqual(-18, moved_units, "Case 7: Moved units are incorrect in -18 character move");
            Assert.AreEqual("gomez thing\r\n", range.GetText(-1), "Case 7: Text is incorrect in -18 character move");

            moved_units = range.MoveEndpointByUnit(TextPatternRangeEndpoint.Start, TextUnit.Character, 4);
            Assert.AreEqual(4, moved_units, "Case 7: Moved units are incorrect in +4 character move");
            Assert.AreEqual("z thing\r\n", range.GetText(-1), "Case 7: Text is incorrect in +4 character move");

            range.ExpandToEnclosingUnit(TextUnit.Paragraph);
            Assert.AreEqual("gomez thing\r\n", range.GetText(-1), "Case 7: Text is incorrect in ExpandToEnclosingUnit");

            // Case #8
            range = textPattern.DocumentRange.Clone();

            moved_units = range.MoveEndpointByUnit(TextPatternRangeEndpoint.Start, TextUnit.Character, 2);
            Assert.AreEqual(2, moved_units, "Case 8: Moved units are incorrect in +2 character move");
            Assert.AreEqual("mez thing\r\nmorticia\twednesday", range.GetText(-1), "Case 8: Text is incorrect in +2 character move");

            moved_units = range.MoveEndpointByUnit(TextPatternRangeEndpoint.End, TextUnit.Character, -16);
            Assert.AreEqual(-16, moved_units, "Case 8: Moved units are incorrect in -16 character move");
            Assert.AreEqual("mez thing\r\nmo", range.GetText(-1), "Case 8: Text is incorrect in -16 character move");

            // XXX: Behaves differently than TextUnit.Line
            range.ExpandToEnclosingUnit(TextUnit.Paragraph);
            Assert.AreEqual("gomez thing\r\nmorticia\twednesday", range.GetText(-1), "Case 8: Text is incorrect in ExpandToEnclosingUnit");
        }
Example #20
0
        private void MoveEndpointByParagraphIntensive(string newline)
        {
            string text = String.Format("apples{0}{0}pears{0}peaches{0}{0}bananas", newline);

            SetText(text);
            Thread.Sleep(500);

            TextPattern      textPattern = (TextPattern)textbox3Element.GetCurrentPattern(TextPattern.Pattern);
            TextPatternRange range       = textPattern.DocumentRange.Clone();

            // NOTE: These all pass successfully on Windows Vista, so
            // think twice before you change anything.
            int moved_units;

            moved_units = range.MoveEndpointByUnit(TextPatternRangeEndpoint.Start, TextUnit.Character, 1);
            Assert.AreEqual(1, moved_units, "Moved units are incorrect in 0 paragraph move");
            Assert.AreEqual(String.Format("pples{0}{0}pears{0}peaches{0}{0}bananas", newline),
                            range.GetText(-1), "Text is incorrect in 0 paragraph move");

            moved_units = range.MoveEndpointByUnit(TextPatternRangeEndpoint.Start, TextUnit.Paragraph, -1);
            Assert.AreEqual(-1, moved_units, "Moved units are incorrect in -1 paragraph move");
            Assert.AreEqual(String.Format("apples{0}{0}pears{0}peaches{0}{0}bananas", newline),
                            range.GetText(-1), "Text is incorrect in -1 paragraph move");

            range = textPattern.DocumentRange.Clone();

            moved_units = range.MoveEndpointByUnit(TextPatternRangeEndpoint.Start, TextUnit.Character, 1);
            Assert.AreEqual(1, moved_units, "Moved units are incorrect in +1 character move");
            Assert.AreEqual(String.Format("pples{0}{0}pears{0}peaches{0}{0}bananas", newline),
                            range.GetText(-1), "Text is incorrect in +1 character move");

            moved_units = range.MoveEndpointByUnit(TextPatternRangeEndpoint.Start, TextUnit.Paragraph, 2);
            Assert.AreEqual(2, moved_units, "Moved units are incorrect in +2 paragraph move");
            Assert.AreEqual(String.Format("pears{0}peaches{0}{0}bananas", newline),
                            range.GetText(-1), "Text is incorrect in +2 paragraph move");

            moved_units = range.MoveEndpointByUnit(TextPatternRangeEndpoint.Start, TextUnit.Paragraph, -1);
            Assert.AreEqual(-1, moved_units, "Moved units are incorrect in first -1 paragraph move");
            Assert.AreEqual(String.Format("{0}pears{0}peaches{0}{0}bananas", newline),
                            range.GetText(-1), "Text is incorrect in -1 paragraph move");

            moved_units = range.MoveEndpointByUnit(TextPatternRangeEndpoint.Start, TextUnit.Paragraph, -1);
            Assert.AreEqual(-1, moved_units, "Moved units are incorrect in first -1 paragraph move");
            Assert.AreEqual(String.Format("apples{0}{0}pears{0}peaches{0}{0}bananas", newline),
                            range.GetText(-1), "Text is incorrect in -1 paragraph move");

            moved_units = range.MoveEndpointByUnit(TextPatternRangeEndpoint.Start, TextUnit.Paragraph, 4);
            Assert.AreEqual(4, moved_units, "Moved units are incorrect in +4 paragraph move");
            Assert.AreEqual(String.Format("{0}bananas", newline),
                            range.GetText(-1), "Text is incorrect in +4 paragraph move");

            moved_units = range.MoveEndpointByUnit(TextPatternRangeEndpoint.Start, TextUnit.Paragraph, 10);
            Assert.AreEqual(2, moved_units, "Moved units are incorrect in +10 paragraph move");
            Assert.AreEqual(String.Empty, range.GetText(-1), "Text is incorrect in +10 paragraph move");

            moved_units = range.MoveEndpointByUnit(TextPatternRangeEndpoint.Start, TextUnit.Paragraph, -10);
            Assert.AreEqual(-6, moved_units, "Moved units are incorrect in -10 paragraph move");
            Assert.AreEqual(String.Format("apples{0}{0}pears{0}peaches{0}{0}bananas", newline),
                            range.GetText(-1), "Text is incorrect in -10 paragraph move");

            // Going bananas yet?
        }
Example #21
0
 public static string GetTextPattern(AutomationElement targetTextElement, TextPattern textPattern)
 {
     return(textPattern.DocumentRange.GetText(-1));
 }
        private void MouseHook_LeftButtonUp(MouseHook.MSLLHOOKSTRUCT mouseStruct)
        {
            mouseHook.Uninstall();
            Point mousePoint = new Point(mouseStruct.pt.x, mouseStruct.pt.y);
            int   hwnd       = User.WindowFromPoint(mouseStruct.pt.x, mouseStruct.pt.y);

            if (0 == hwnd)
            {
                return;
            }
            int root = User.GetAncestor((IntPtr)hwnd, User.GA_ROOT);

            int pid = 0;

            User.GetWindowThreadProcessId((IntPtr)root, ref pid);



            Process[] processlist = Process.GetProcesses();
            foreach (Process p in processlist)
            {
                if (p.Id == pid)
                {
                    mainwndText = p.MainWindowTitle;
                    processName = p.ProcessName;
                    //processPath = p.MainModule.FileName;
                }
            }
            Automation.Condition        condition     = new PropertyCondition(AutomationElement.NameProperty, mainwndText);
            AutomationElement           appElement    = rootElement.FindFirst(TreeScope.Children, condition);
            AutomationElementCollection theCollection = appElement.FindAll(TreeScope.Descendants, Automation.Condition.TrueCondition);

            if (null == appElement)
            {
                return;
            }
            AutomationElement focusElement = AutomationElement.FromPoint(mousePoint);

            switch (focusElement.Current.FrameworkId)
            {
            case "WPF":
                switch (focusElement.Current.ClassName)
                {
                case "TextBox":
                {
                    ValuePattern pattern = focusElement.GetCurrentPattern(ValuePattern.Pattern) as ValuePattern;
                    tb_detail.Text += pattern.Current.Value + "\r\n";
                }
                break;

                case "TextBlock":
                case "Text":
                {
                    tb_detail.Text += focusElement.Current.Name + "\r\n";
                }
                break;

                case "RichTextBox":
                {
                    TextPattern pattern     = focusElement.GetCurrentPattern(TextPattern.Pattern) as TextPattern;
                    string      controlText = pattern.DocumentRange.GetText(-1);
                    tb_detail.Text += controlText + "\r\n";
                }
                break;
                }
                break;

            case "Win32":
                if (focusElement.Current.ControlType == ControlType.Document ||
                    focusElement.Current.ControlType == ControlType.Edit)
                {
                    TextPattern pattern     = focusElement.GetCurrentPattern(TextPattern.Pattern) as TextPattern;
                    string      controlText = pattern.DocumentRange.GetText(-1);
                    tb_detail.Text += controlText + "\r\n";
                }
                else if (focusElement.Current.ControlType == ControlType.Text)
                {
                    tb_detail.Text += focusElement.Current.Name + "\r\n";
                }
                break;

            case "WinForm":
                tb_detail.Text += focusElement.Current.Name + "\r\n";
                break;

            case "Silverlight":
                break;

            case "SWT":
                break;

            default:
                break;
            }
            TreeWalker        tWalker       = TreeWalker.ControlViewWalker;
            AutomationElement parentElement = tWalker.GetParent(focusElement);

            if (parentElement == AutomationElement.RootElement)
            {
                return;
            }
            while (true)
            {
                AutomationElement element = tWalker.GetParent(parentElement);
                if (element == AutomationElement.RootElement)
                {
                    break;
                }
                else
                {
                    parentElement = element;
                }
            }
        }
Example #23
0
        static void Main(string[] args)
        {
            try
            {
                Console.WriteLine("\nBegin WinForm UIAutomation test run\n");
                // launch Form1 application
                // get refernce to main Form control
                // get references to user controls
                // manipulate application
                // check resulting state and determine pass/fail

                Console.WriteLine("\nBegin WinForm UIAutomation test run\n");
                Console.WriteLine("Launching WinFormTest application");
                //启动被测试的程序
                Process p = Process.Start(@"E:\Project\WinFormTest\WinFormTest\bin\Debug\WinFormTest.exe");

                //自动化根元素
                AutomationElement aeDeskTop = AutomationElement.RootElement;

                Thread.Sleep(2000);
                AutomationElement aeForm = AutomationElement.FromHandle(p.MainWindowHandle);
                //获得对主窗体对象的引用,该对象实际上就是 Form1 应用程序(方法一)
                //if (null == aeForm)
                //{
                //    Console.WriteLine("Can not find the WinFormTest from.");
                //}

                //获得对主窗体对象的引用,该对象实际上就是 Form1 应用程序(方法二)
                int numWaits = 0;
                do
                {
                    Console.WriteLine("Looking for WinFormTest……");
                    //查找第一个自动化元素
                    aeForm = aeDeskTop.FindFirst(TreeScope.Children, new PropertyCondition(
                                                     AutomationElement.NameProperty, "Form1"));
                    ++numWaits;
                    Thread.Sleep(100);
                } while (null == aeForm && numWaits < 50);
                if (null == aeForm)
                {
                    throw new NullReferenceException("Failed to find WinFormTest.");
                }
                else
                {
                    Console.WriteLine("Found it!");
                }

                Console.WriteLine("Finding all user controls");
                //找到第一次出现的Button控件
                AutomationElement aeButton = aeForm.FindFirst(TreeScope.Children,
                                                              new PropertyCondition(AutomationElement.NameProperty, "button1"));

                //找到所有的TextBox控件
                AutomationElementCollection aeAllTextBoxes = aeForm.FindAll(TreeScope.Children,
                                                                            new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit));

                // 控件初始化的顺序是先初始化后添加到控件
                // this.Controls.Add(this.textBox3);
                // this.Controls.Add(this.textBox2);
                // this.Controls.Add(this.textBox1);

                AutomationElement aeTextBox1 = aeAllTextBoxes[2];
                AutomationElement aeTextBox2 = aeAllTextBoxes[1];
                AutomationElement aeTextBox3 = aeAllTextBoxes[0];

                Console.WriteLine("Settiing input to '30'");
                //通过ValuePattern设置TextBox1的值
                ValuePattern vpTextBox1 = (ValuePattern)aeTextBox1.GetCurrentPattern(ValuePattern.Pattern);
                vpTextBox1.SetValue("30");
                Console.WriteLine("Settiing input to '50'");
                //通过ValuePattern设置TextBox2的值
                ValuePattern vpTextBox2 = (ValuePattern)aeTextBox2.GetCurrentPattern(ValuePattern.Pattern);
                vpTextBox2.SetValue("50");
                Thread.Sleep(1500);
                Console.WriteLine("Clickinig on button1 Button.");
                //通过InvokePattern模拟点击按钮
                InvokePattern ipClickButton1 = (InvokePattern)aeButton.GetCurrentPattern(InvokePattern.Pattern);
                ipClickButton1.Invoke();
                Thread.Sleep(1500);

                //验证计算的结果与预期的结果是否相符合
                Console.WriteLine("Checking textBox3 for '80'");
                TextPattern tpTextBox3 = (TextPattern)aeTextBox3.GetCurrentPattern(TextPattern.Pattern);
                string      result     = tpTextBox3.DocumentRange.GetText(-1);//获取textbox3中的值
                //获取textbox3中的值
                //string result = (string)aeTextBox2.GetCurrentPropertyValue(ValuePattern.ValueProperty);
                if ("80" == result)
                {
                    Console.WriteLine("Found it.");
                    Console.WriteLine("TTest scenario: *PASS*");
                }
                else
                {
                    Console.WriteLine("Did not find it.");
                    Console.WriteLine("Test scenario: *FAIL*");
                }

                Console.WriteLine("Close application in 5 seconds.");
                Thread.Sleep(5000);
                //实现关闭被测试程序
                WindowPattern wpCloseForm = (WindowPattern)aeForm.GetCurrentPattern(WindowPattern.Pattern);
                wpCloseForm.Close();

                Console.WriteLine("\nEnd test run\n");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Fatal error: " + ex.Message);
            }
        }
 /// <summary>
 /// Exposes methods and properties used in batch styling of text.  In contrast to the TextAnnotator
 /// class, this class is meant to be used in the styling of *formatted* strings, i.e. strings that
 /// follow the "{0}, {1}...{n}" pattern.
 /// </summary>
 /// <param name="defaultColor">The color to be associated with unstyled text.</param>
 /// <param name="formatToken">A regular expression representing the format token.  By default,
 /// the TextFormatter will use a regular expression that matches the "{0}, {1}...{n}" pattern.</param>
 public TextFormatter(Color defaultColor, string formatToken)
 {
     this.defaultColor = defaultColor;
     textPattern = new TextPattern(defaultFormatToken);
 }
        /// <summary>
        /// Returns the plain text of the text range.
        /// </summary>
        /// <param name="control">The UI Automation element</param>
        /// <param name="maxLength">The maximum length of the string to return. Use -1 if no limit is required</param>
        /// <returns>
        /// The plain text of the text range, possibly truncated at the specified maxLength
        /// </returns>
        internal static string GetText(AutomationElement control, int maxLength)
        {
            TextPattern pat = (TextPattern)CommonUIAPatternHelpers.CheckPatternSupport(TextPattern.Pattern, control);

            return(pat.DocumentRange.GetText(maxLength));
        }
        /// <summary>
        /// Retrieves an array of disjoint text ranges from a text container where each text range begins with the first
        /// partially visible line through to the end of the last partially visible line
        /// </summary>
        /// <param name="control">The UI Automation element</param>
        /// <returns>
        /// The collection of visible text ranges within the container or an empty array
        /// </returns>
        internal static TextPatternRange[] GetVisibleRanges(AutomationElement control)
        {
            TextPattern pat = (TextPattern)CommonUIAPatternHelpers.CheckPatternSupport(TextPattern.Pattern, control);

            return(pat.GetVisibleRanges());
        }
Example #27
0
		internal TextPatternRange (TextPattern textPattern, ITextPatternRange source)
		{
			TextPattern = textPattern;
			this.source = source;
		}
        /// <summary>
        /// Gets a value that specifies whether a text provider supports selection and, if so, the type of selection supported
        /// </summary>
        /// <param name="control">The UI Automation element</param>
        /// <returns>
        ///   <see cref="SupportedTextSelection"/> None, Single, or Multiple
        /// </returns>
        internal static SupportedTextSelection GetSupportedTextSelection(AutomationElement control)
        {
            TextPattern pat = (TextPattern)CommonUIAPatternHelpers.CheckPatternSupport(TextPattern.Pattern, control);

            return(pat.SupportedTextSelection);
        }
Example #29
0
        internal static TextPatternRange [] Wrap(SafeTextRangeHandle [] hTextRanges, TextPattern pattern)
        {
            if (hTextRanges == null)
                return null;

            TextPatternRange[] ranges = new TextPatternRange[hTextRanges.Length];
            for (int i = 0; i < hTextRanges.Length; i++)
            {
                // if invalid, leave as null
                if (!hTextRanges[i].IsInvalid)
                {
                    ranges[i] = new TextPatternRange(hTextRanges[i], pattern);
                }
            }
            return ranges;
        }
Example #30
0
 internal TextPatternRange(TextPattern textPattern, ITextPatternRange source)
 {
     TextPattern = textPattern;
     this.source = source;
 }
        public void GetMatches_ReturnsOneMatchLocation_WhenIdenticalStringIsMatchedAgainst()
        {
            TextPattern pattern = new TextPattern(dummyString);

            Assert.Equal(pattern.GetMatches(dummyString).Count(), 1);
        }
Example #32
0
        public static string GetText(AutomationElement element)
        {
            TextPattern currentPattern = AutomationPatternHelper.GetTextPattern(element);

            return(currentPattern.DocumentRange.GetText(-1));
        }
 public TextPatternPropertyObject(TextPattern pattern)
 {
     this._pattern = pattern;
 }
Example #34
0
        public void GetMatchLocations_ReturnsOneMatchLocation_WhenIdenticalStringIsMatchedAgainst()
        {
            TextPattern pattern = new TextPattern(dummyString);

            Assert.Single(pattern.GetMatchLocations(dummyString));
        }
Example #35
0
 internal static TextPatternRange[] Wrap(UIAutomationClient.IUIAutomationTextRangeArray ranges, TextPattern pattern)
 {
     if (ranges == null)
     {
         return null;
     }
     TextPatternRange[] rangeArray = new TextPatternRange[ranges.Length];
     for (int i = 0; i < ranges.Length; i++)
     {
         rangeArray[i] = new TextPatternRange(ranges.GetElement(i), pattern);
     }
     return rangeArray;
 }
Example #36
0
        //需要传一个IE窗口标题的参数, 如上海清算所招聘后台管理系统
        static void Main(string[] args)
        {
            AutomationElement desktop = AutomationElement.RootElement;

            Thread.Sleep(3000);
            try
            {
                String title = null;
                if (args.Length == 1)
                {
                    title = args[0] + " - Internet Explorer";
                }
                //IE弹出窗口
                var downloadWin = desktop.FindFirst(TreeScope.Children,
                                                    new AndCondition(
                                                        new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Window),
                                                        new PropertyCondition(AutomationElement.NameProperty, title) //"上海清算所招聘后台管理系统 - Internet Explorer"
                                                        ));

                //下拉箭头
                Condition dropDownCondition = new AndCondition(
                    new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.SplitButton),
                    new PropertyCondition(AutomationElement.NameProperty, ""));

                var           dropDownBtn = downloadWin.FindFirst(TreeScope.Descendants, dropDownCondition);
                InvokePattern invoke      = (InvokePattern)dropDownBtn.GetCurrentPattern(InvokePattern.Pattern);
                invoke.Invoke();

                Thread.Sleep(2000);
                //选择另存为
                Condition savaAsCondition = new AndCondition(
                    new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.MenuItem),
                    new PropertyCondition(AutomationElement.NameProperty, "另存为(A)"));
                var savaAsMenu = desktop.FindFirst(TreeScope.Descendants, savaAsCondition);
                ((InvokePattern)savaAsMenu.GetCurrentPattern(InvokePattern.Pattern)).Invoke();
                Thread.Sleep(3000);

                //另存为对话框
                var savaAsWin = desktop.FindFirst(TreeScope.Children,
                                                  new AndCondition(
                                                      new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Window),
                                                      new PropertyCondition(AutomationElement.NameProperty, "另存为")));

                Condition fileNameCondition = new AndCondition(
                    new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit),
                    new PropertyCondition(AutomationElement.NameProperty, "文件名:"));

                var         fileNameTxt  = savaAsWin.FindFirst(TreeScope.Descendants, fileNameCondition);
                TextPattern valuePattern = (TextPattern)fileNameTxt.GetCurrentPattern(TextPattern.Pattern);
                string      fileName     = valuePattern.DocumentRange.GetText(-1); //取文件名

                String fullPath = @"D:\autoItDownload\" + fileName;
                String iniFile  = @"D:\autoItDownload\downloadFileFullPath.ini";

                if (File.Exists(fullPath))
                {
                    File.Delete(fullPath);
                }

                try
                {
                    using (StreamWriter sw = new StreamWriter(iniFile))
                    {
                        sw.Write(fullPath);
                        sw.Flush();
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }

                ValuePattern name = (ValuePattern)fileNameTxt.GetCurrentPattern(ValuePattern.Pattern);
                name.SetValue(fullPath);

                //save
                Condition saveCondition = new AndCondition(
                    new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Button),
                    new PropertyCondition(AutomationElement.NameProperty, "保存(S)"));

                var saveBtn = savaAsWin.FindFirst(TreeScope.Descendants, saveCondition);
                ((InvokePattern)saveBtn.GetCurrentPattern(InvokePattern.Pattern)).Invoke();
                Thread.Sleep(5000);

                //close the window
                Condition closeCondition = new AndCondition(
                    new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Button),
                    new PropertyCondition(AutomationElement.NameProperty, "关闭"));
                var closeBtn = downloadWin.FindFirst(TreeScope.Descendants, closeCondition);
                ((InvokePattern)closeBtn.GetCurrentPattern(InvokePattern.Pattern)).Invoke();
            }
            catch (Exception ex)
            {
                Console.WriteLine("下载文件异常");
                Console.WriteLine(ex.Message);
            }
        }
Example #37
0
 internal static TextPatternRange Wrap(UIAutomationClient.IUIAutomationTextRange range, TextPattern pattern)
 {
     Debug.Assert(pattern != null);
     if (range == null)
     {
         return(null);
     }
     else
     {
         return(new TextPatternRange(range, pattern));
     }
 }
Example #38
0
        static void Main(string[] args)
        {
            // テスト自動化の一般的な処理として、ハーネスの最上位のtry/catch ブロックでラップして致命的なエラーに対処している。
            try {
                Console.WriteLine("\nBegin WPF UIAutomation test run\n");
                // テストアプリを起動。
                Process p = null;
                p = Process.Start("..\\..\\..\\WPFUITest\\bin\\Debug\\WPFUITest.exe");

                // sleep(遅延ループ)
                int ct = 0;
                do
                {
                    Console.WriteLine("Looking for CryptoCalc process. . . ");
                    ++ct;
                    Thread.Sleep(100);
                } while (p == null && ct < 50);

                // 遅延ループがタイムアウトになったか、またはAUTプロセスが見つかったかを判断する。
                if (p == null)
                {
                    throw new Exception("Failed to find CryptoCalc process");
                }
                else
                {
                    Console.WriteLine("Found CryptoCalc process");
                }

                // テストアプリを参照するため、全ての親WindowとなるDesktopを取得する。
                Console.WriteLine("\nGetting Desktop");
                AutomationElement aeDesktop = null;
                aeDesktop = AutomationElement.RootElement;
                // DeskTopが取得できたか?
                if (aeDesktop == null)
                {
                    throw new Exception("Unable to get Desktop");
                }
                else
                {
                    Console.WriteLine("Found Desktop\n");
                }

                // DeskTopからテストアプリを取得する。
                AutomationElement aeCryptoCalc = null;
                int numWaits = 0;
                do
                {
                    Console.WriteLine("Looking for CryptoCalc main window. . . ");
                    aeCryptoCalc = aeDesktop.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.NameProperty, "Window1"));
                    ++numWaits;
                    Thread.Sleep(200);
                } while (aeCryptoCalc == null && numWaits < 50);
                // テストアプリが取得できたか?
                if (aeCryptoCalc == null)
                {
                    throw new Exception("Failed to find CryptoCalc main window");
                }
                else
                {
                    Console.WriteLine("Found CryptoCalc main window");
                }

#if false // 自動テストがてら、エビデンスのキャプチャもとっちゃおう!というコード
                // テストアプリのウィンドウ位置を取得する(キャプチャに使用)
                var rtWindow = aeCryptoCalc.Current.BoundingRectangle;
#endif

                // テストアプリからボタンを取得する。
                // Buttonコントロールは静的コントロールであるため、コントロールへの参照にアクセスする前に遅延ループ手法を使用する必要はない。(動的コントロールの場合は必要になる!)
                Console.WriteLine("\nGetting all user controls");
                AutomationElement aeButton = null;
                aeButton = aeCryptoCalc.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.NameProperty, "Compute"));
                // ボタンが取得できたか?
                if (aeButton == null)
                {
                    throw new Exception("No compute button");
                }
                else
                {
                    Console.WriteLine("Got Compute button");
                }

                // テストアプリからテキストボックスを取得する。
#if false
                // TextBoxコントロール(に限るのかな?)はNameプロパティを受け取らないため、AutomationIdPropertyを使用する。
                AutomationElement aeTextBox1 = null;
                aeTextBox1 = aeCryptoCalc.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.AutomationIdProperty, "TextBox1"));
#else
                // または、こんな方法もあるよ!
                AutomationElementCollection aeAllTextBoxes = null;
                aeAllTextBoxes = aeCryptoCalc.FindAll(TreeScope.Children, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit));
                if (aeAllTextBoxes == null)
                {
                    throw new Exception("No textboxes collection");
                }
                else
                {
                    Console.WriteLine("Got textboxes collection");
                }

                AutomationElement aeTextBox1 = null;
                AutomationElement aeTextBox2 = null;
                aeTextBox1 = aeAllTextBoxes[0];
                aeTextBox2 = aeAllTextBoxes[1];
                if (aeTextBox1 == null || aeTextBox2 == null)
                {
                    throw new Exception("TextBox1 or TextBox2 not found");
                }
                else
                {
                    Console.WriteLine("Got TextBox1 and TextBox2");
                }
#endif

                // テストアプリからラジオボタンを取得する。
                AutomationElement aeRadioButton3 = null;
                aeRadioButton3 = aeCryptoCalc.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.NameProperty, "DES Encrypt"));
                if (aeRadioButton3 == null)
                {
                    throw new Exception("No RadioButton3");
                }
                else
                {
                    Console.WriteLine("Got RadioButton3");
                }


                // テキストボックス1にHello!を入力する。
                // 直接参照するのではなく、ValuePatternオブジェクト経由のSetValueで入力する。
                Console.WriteLine("\nSetting input to 'Hello!'");
                ValuePattern vpTextBox1 = (ValuePattern)aeTextBox1.GetCurrentPattern(ValuePattern.Pattern);
                vpTextBox1.SetValue("Hello!");

#if false // 自動テストがてら、エビデンスのキャプチャもとっちゃおう!というコード
                // キャプチャをとる。
                Bitmap bmp = new Bitmap((int)rtWindow.Width, (int)rtWindow.Height, PixelFormat.Format32bppArgb);
                using (var g = Graphics.FromImage(bmp)) {
                    g.CopyFromScreen(int.Parse(rtWindow.X.ToString())
                                     , int.Parse(rtWindow.Y.ToString())
                                     , 0
                                     , 0
                                     , new System.Drawing.Size((int)rtWindow.Size.Width, (int)rtWindow.Size.Height)
                                     , CopyPixelOperation.SourceCopy);
                }
                string filePath = @"c:\screen.bmp";
                bmp.Save(filePath, ImageFormat.Bmp);
#endif

                // ラジオボタンにチェックを入れる。
                Console.WriteLine("Selecting 'DES Encrypt' ");
                SelectionItemPattern spSelectRadioButton3 = (SelectionItemPattern)aeRadioButton3.GetCurrentPattern(SelectionItemPattern.Pattern);
                spSelectRadioButton3.Select();

                // ボタンをクリックする。
                Console.WriteLine("\nClicking on Compute button");
                InvokePattern ipClickButton1 = (InvokePattern)aeButton.GetCurrentPattern(InvokePattern.Pattern);
                ipClickButton1.Invoke();
                Thread.Sleep(1500);

                // テキストボックス2の値を確認する。
                Console.WriteLine("\nChecking TextBox2 for '91-1E-84-41-67-4B-FF-8F'");
                TextPattern tpTextBox2 = (TextPattern)aeTextBox2.GetCurrentPattern(TextPattern.Pattern);
                string      result     = tpTextBox2.DocumentRange.GetText(-1);
                // これでもOK
                //string result = (string)aeTextBox2.GetCurrentPropertyValue(ValuePattern.ValueProperty);
                if (result == "91-1E-84-41-67-4B-FF-8F")
                {
                    Console.WriteLine("Found it");
                    Console.WriteLine("\nTest scenario: Pass");
                }
                else
                {
                    Console.WriteLine("Did not find it");
                    Console.WriteLine("\nTest scenario: *FAIL*");
                }


                // Menuコントロールを調べ、テストアプリを終了する。
                Console.WriteLine("\nClicking on File-Exit item in 5 seconds");
                Thread.Sleep(5000);
                AutomationElement aeFile = null;
                aeFile = aeCryptoCalc.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.NameProperty, "File"));
                if (aeFile == null)
                {
                    throw new Exception("Could not find File menu");
                }
                else
                {
                    Console.WriteLine("Got File menu");
                }

                // [File]項目を展開する。
                Console.WriteLine("Clicking on 'File'");
                ExpandCollapsePattern expClickFile = (ExpandCollapsePattern)aeFile.GetCurrentPattern(ExpandCollapsePattern.Pattern);
                expClickFile.Expand();

                // [Exit]をクリックする。
                AutomationElement aeFileExit = null;
                aeFileExit = aeCryptoCalc.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.NameProperty, "Exit"));
                if (aeFileExit == null)
                {
                    throw new Exception("Could not find File-Exit");
                }
                else
                {
                    Console.WriteLine("Got File-Exit");
                }
                InvokePattern ipFileExit = (InvokePattern)aeFileExit.GetCurrentPattern(InvokePattern.Pattern);
                ipFileExit.Invoke();
                Console.WriteLine("\nEnd automation\n");


                //
                Console.WriteLine("\nEnd automation\n");
            } catch (Exception ex) {
                Console.WriteLine("Fatal: " + ex.Message);
            }
        }
Example #39
0
        public void FaultAppendText()
        {
            //This is a work-around, Xunit moves the reference dll's at run time so we need to call register
            //from the test, instead of TestApiCore.
            string processorArch = DetectProccessorArchitecture();

            ComRegistrar.Register(@".\FaultInjectionEngine\" + processorArch + @"\FaultInjectionEngine.dll");

            string sampleAppPath = "SampleApp.exe";

            //Create the FaultRule and FaultSession
            FaultRule rule = new FaultRule(
                "SampleApp.Window1.Append(string, string)",
                BuiltInConditions.TriggerOnEveryCall,
                BuiltInFaults.ReturnValueFault(""));

            FaultSession session = new FaultSession(rule);

            //Start the app
            ProcessStartInfo        psi     = session.GetProcessStartInfo(sampleAppPath);
            OutOfProcessApplication testApp = new OutOfProcessApplication(
                new OutOfProcessApplicationSettings
            {
                ProcessStartInfo = psi,
                ApplicationImplementationFactory = new UIAutomationOutOfProcessApplicationFactory()
            });

            testApp.Start();


            try
            {
                testApp.WaitForMainWindow(TimeSpan.FromSeconds(15));

                // Discover various elements in the UI
                AutomationElement mainWindowElement = (AutomationElement)testApp.MainWindow;
                AutomationElement inputTextBox      = AutomationUtilities.FindElementsById(mainWindowElement, "inputTextBox")[0];
                AutomationElement outputTextBox     = AutomationUtilities.FindElementsById(mainWindowElement, "outputTextBox")[0];
                AutomationElement appendButton      = AutomationUtilities.FindElementsById(mainWindowElement, "appendButton")[0];

                // Click on the input text box and simulate typing
                string inputText    = "TestTest";
                string expectedText = ""; //expected text should be nothing since we intercept the Append method

                WindowPattern winPattern = mainWindowElement.GetCurrentPattern(WindowPattern.Pattern) as WindowPattern;
                Helpers.MoveToAndClick(inputTextBox);
                winPattern.WaitForInputIdle(inputWaitTime);
                Microsoft.Test.Input.Keyboard.Type(inputText);
                winPattern.WaitForInputIdle(inputWaitTime);

                // Now click the button
                Helpers.MoveToAndClick(appendButton);
                winPattern.WaitForInputIdle(inputWaitTime);

                // Now, get the text of the outputTextBox and compare it against what's expected
                // Fail the test if expected != actual
                TextPattern textPattern = outputTextBox.GetCurrentPattern(TextPattern.Pattern) as TextPattern;
                string      actualText  = textPattern.DocumentRange.GetText(-1);

                // Report the test result
                Assert.Equal <string>(expectedText, actualText);
            }
            finally
            {
                // Close the tested application
                testApp.Close();
            }
        }
        /// <summary>
        /// Returns the degenerate (empty) text range nearest to the specified screen coordinates
        /// </summary>
        /// <param name="control">The UI Automation element</param>
        /// <param name="screenLocation">The location in screen coordinates</param>
        /// <returns>
        /// A degenerate range nearest the specified location
        /// </returns>
        internal static TextPatternRange GetRangeFromPoint(AutomationElement control, Point screenLocation)
        {
            TextPattern pat = (TextPattern)CommonUIAPatternHelpers.CheckPatternSupport(TextPattern.Pattern, control);

            return(pat.RangeFromPoint(screenLocation));
        }