TextPatternRange.Move(TextUnit, Int32) Метод

Определение

Перемещает текстовый диапазон на заданное количество единиц текста.

public:
 int Move(System::Windows::Automation::Text::TextUnit unit, int count);
public int Move (System.Windows.Automation.Text.TextUnit unit, int count);
member this.Move : System.Windows.Automation.Text.TextUnit * int -> int
Public Function Move (unit As TextUnit, count As Integer) As Integer

Параметры

unit
TextUnit

Граница единицы текста.

count
Int32

Количество единиц текста, на которое следует выполнить перемещение. Положительное значение соответствует перемещению текстового диапазона вперед, отрицательное — назад, а при значении 0 перемещение не выполняется.

Возвращаемое значение

Количество единиц текста, на которое выполнено перемещение. Оно может быть меньше запрошенного количества, если одна из новых конечных точек текстового диапазона больше или меньше конечных точек DocumentRange.

Примеры

/// -------------------------------------------------------------------
/// <summary>
/// Starts the target application and returns the AutomationElement 
/// obtained from the targets window handle.
/// </summary>
/// <param name="exe">
/// The target application.
/// </param>
/// <param name="filename">
/// The text file to be opened in the target application
/// </param>
/// <returns>
/// An AutomationElement representing the target application.
/// </returns>
/// -------------------------------------------------------------------
private AutomationElement StartTarget(string exe, string filename)
{
    // Start text editor and load with a text file.
    Process p = Process.Start(exe, filename);

    // targetApp --> the root AutomationElement.
    AutomationElement targetApp =
        AutomationElement.FromHandle(p.MainWindowHandle);

    return targetApp;
}
''' -------------------------------------------------------------------
''' <summary>
''' Starts the target application and returns the AutomationElement 
''' obtained from the targets window handle.
''' </summary>
''' <param name="exe">
''' The target application.
''' </param>
''' <param name="filename">
''' The text file to be opened in the target application
''' </param>
''' <returns>
''' An AutomationElement representing the target application.
''' </returns>
''' -------------------------------------------------------------------
Private Function StartTarget( _
ByVal exe As String, ByVal filename As String) As AutomationElement
    ' Start text editor and load with a text file.
    Dim p As Process = Process.Start(exe, filename)

    ' targetApp --> the root AutomationElement.
    Dim targetApp As AutomationElement
    targetApp = AutomationElement.FromHandle(p.MainWindowHandle)

    Return targetApp
End Function
/// -------------------------------------------------------------------
/// <summary>
/// Obtain the text control of interest from the target application.
/// </summary>
/// <param name="targetApp">
/// The target application.
/// </param>
/// <returns>
/// An AutomationElement that represents a text provider..
/// </returns>
/// -------------------------------------------------------------------
private AutomationElement GetTextElement(AutomationElement targetApp)
{
    // The control type we're looking for; in this case 'Document'
    PropertyCondition cond1 =
        new PropertyCondition(
        AutomationElement.ControlTypeProperty,
        ControlType.Document);

    // The control pattern of interest; in this case 'TextPattern'.
    PropertyCondition cond2 = 
        new PropertyCondition(
        AutomationElement.IsTextPatternAvailableProperty, 
        true);

    AndCondition textCondition = new AndCondition(cond1, cond2);

    AutomationElement targetTextElement =
        targetApp.FindFirst(TreeScope.Descendants, textCondition);

    // If targetText is null then a suitable text control was not found.
    return targetTextElement;
}
''' -------------------------------------------------------------------
''' <summary>
''' Obtain the text control of interest from the target application.
''' </summary>
''' <param name="targetApp">
''' The target application.
''' </param>
''' <returns>
''' An AutomationElement. representing a text control.
''' </returns>
''' -------------------------------------------------------------------
Private Function GetTextElement(ByVal targetApp As AutomationElement) As AutomationElement
    ' The control type we're looking for; in this case 'Document'
    Dim cond1 As PropertyCondition = _
        New PropertyCondition( _
        AutomationElement.ControlTypeProperty, _
        ControlType.Document)

    ' The control pattern of interest; in this case 'TextPattern'.
    Dim cond2 As PropertyCondition = _
        New PropertyCondition( _
        AutomationElement.IsTextPatternAvailableProperty, _
        True)

    Dim textCondition As AndCondition = New AndCondition(cond1, cond2)

    Dim targetTextElement As AutomationElement = _
        targetApp.FindFirst(TreeScope.Descendants, textCondition)

    ' If targetText is null then a suitable text control was not found.
    Return targetTextElement
End Function
/// -------------------------------------------------------------------
/// <summary>
/// Moves a text range a specified number of text units. The text range 
/// is the current selection.
/// </summary>
/// <param name="targetTextElement">
/// The AutomationElment that represents a text control.
/// </param>
/// <param name="textUnit">
/// The text unit value.
/// </param>
/// <param name="units">
/// The number of text units to move.
/// </param>
/// <param name="direction">
/// Direction to move the text range. Valid values are -1, 0, 1.
/// </param>
/// <returns>
/// The number of text units actually moved. This can be less than the 
/// number requested if either of the new text range endpoints is 
/// greater than or less than the DocumentRange endpoints. 
/// </returns>
/// <remarks>
/// Moving the text range does not modify the text source in any way. 
/// Only the text range starting and ending endpoints are modified.
/// </remarks>
/// -------------------------------------------------------------------
private Int32 MoveSelection(
    AutomationElement targetTextElement, 
    TextUnit textUnit,
    int units,
    int direction)
{
    TextPattern textPattern =
        targetTextElement.GetCurrentPattern(TextPattern.Pattern) 
        as TextPattern;

    if (textPattern == null)
    {
        // Target control doesn't support TextPattern.
        return -1;
    }

    TextPatternRange[] currentSelection = textPattern.GetSelection();

    if (currentSelection.Length > 1)
    {
        // For this example, we cannot move more than one text range.
        return -1;
    }

    return currentSelection[0].Move(textUnit, Math.Sign(direction) * units);
}
''' -------------------------------------------------------------------
''' <summary>
''' Moves a text range a specified number of text units.
''' </summary>
''' <param name="targetTextElement">
''' The AutomationElement that represents a text control.
''' </param>
''' <param name="textUnit">
''' The text unit value.
''' </param>
''' <param name="units">
''' The number of text units to move.
''' </param>
''' <param name="direction">
''' Direction to move the text range. Valid values are -1, 0, 1.
''' </param>
''' <returns>
''' The number of text units actually moved. This can be less than the 
''' number requested if either of the new text range endpoints is 
''' greater than or less than the DocumentRange endpoints. 
''' </returns>
''' <remarks>
''' Moving the text range does not modify the text source in any way. 
''' Only the text range starting and ending endpoints are modified.
''' </remarks>
''' -------------------------------------------------------------------
Private Function MoveSelection( _
    ByVal targetTextElement As AutomationElement, _
    ByVal textUnit As TextUnit, _
    ByVal units As Integer, _
    ByVal direction As Integer) As Integer

    Dim textPattern As TextPattern = _
    DirectCast( _
    targetTextElement.GetCurrentPattern(textPattern.Pattern), _
    TextPattern)

    If (textPattern Is Nothing) Then
        ' Target control doesn't support TextPattern.
        Return -1
    End If

    Dim currentSelection As TextPatternRange() = _
    textPattern.GetSelection()

    If (currentSelection.Length > 1) Then
        ' For this example, we cannot move more than one text range.
        Return -1
    End If

    Return currentSelection(0).Move(textUnit, Math.Sign(direction) * units)
End Function

Комментарии

Для обхода содержимого текстового диапазона в фоновом режиме применяется ряд шагов для успешного выполнения метода Move .

  1. Текстовый диапазон нормализован, т. е. он свернут до вырожденного диапазона в конечной точке Start , что делает конечную точку End избыточной. Этот шаг необходим для устранения неоднозначности в ситуациях, когда текстовый диапазон охватывает границы unit ; например, "{U}RL https://www.microsoft.com/ внедрен в текст", где "{" и "}" являются конечными точками диапазона текста.

  2. Результирующий диапазон перемещается в DocumentRange в начало запрошенной границы unit .

  3. Диапазон перемещается вперед или назад в DocumentRange на запрошенное число границ unit .

  4. Затем диапазон расширяется из вырожденного состояния путем перемещения конечной точки End на одну запрошенную границу unit .

Корректировки диапазона по move & ExpandToEnclosingUnit
Примеры корректировки текстового диапазона для Move() и ExpandToEnclosingUnit()

Текстовое содержимое (или внутренний текст) текстового контейнера и внедренного объекта, например гиперссылки или ячейки таблицы, предоставляется в виде единого непрерывного текстового потока как в представлении элемента управления, так и в представлении содержимого дерева модель автоматизации пользовательского интерфейса; границы объектов игнорируются. Если клиент автоматизации пользовательского интерфейса извлекает текст с целью вывода, интерпретации или анализа, текстовый диапазон следует проверить на соответствие особым случаям, например таблице с текстовым содержимым или другим внедренным объектам. Это можно сделать путем вызова GetChildren для получения AutomationElement для каждого внедренного объекта, а затем вызова RangeFromChild для получения текстового диапазона для каждого элемента. Это выполняется рекурсивно, пока не будет извлечено все текстовое содержимое.

Диапазоны текста, охватываемые внедренными объектами.
Пример текстового потока с внедренными объектами и их диапазонами

Move учитывает как скрытый, так и видимый текст. Клиент модель автоматизации пользовательского интерфейса может проверка IsHiddenAttribute для видимости текста.

Move откладывает до следующего по величине TextUnit поддерживаемого, если заданный TextUnit не поддерживается элементом управления .

Ниже приведен порядок от наименьшей единицы до наибольшего.

Примечание

Текст не изменяется каким-либо образом, так как диапазон текста просто охватывает другую часть текста.

Применяется к

См. также раздел