TextPatternRange.Move(TextUnit, Int32) Método

Definição

Move o intervalo de texto conforme o número de unidades de texto especificado.

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

Parâmetros

unit
TextUnit

O limite da unidade de texto.

count
Int32

O número de unidades de texto a serem movidas. Um valor positivo move o intervalo de texto para frente, um valor negativo move o intervalo de texto para trás e 0 não tem nenhum efeito.

Retornos

O número de unidades realmente movidas. Isso pode ser menos que o número solicitado se um dos pontos de extremidade do novo intervalo de texto for maior ou menor do que os pontos de extremidade de DocumentRange.

Exemplos

/// -------------------------------------------------------------------
/// <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

Comentários

Quando é necessário percorrer o conteúdo de um intervalo de texto, uma série de etapas são envolvidas nos bastidores para que o método Move seja executado com êxito.

  1. O intervalo de texto é normalizado; ou seja, ele é recolhido a um intervalo degenerado no ponto de extremidade Start, o que torna o ponto de extremidade End supérfluo. Esta etapa é necessária para remover a ambiguidade em situações em que um intervalo de texto abrange unit limites; por exemplo, "{A U}RL https://www.microsoft.com/ está inserida no texto" em que "{" e "}" são os pontos de extremidade do intervalo de texto.

  2. O intervalo resultante é movido para trás no DocumentRange para o início do limite unit solicitado.

  3. O intervalo é movido para frente ou para trás no DocumentRange o número solicitado de limites unit.

  4. Em seguida, o intervalo é expandido de um estado de intervalo degenerado movendo o ponto de extremidade End um limite unit solicitado.

Ajustes de intervalo por Move & ExpandToEnclosingUnit
Exemplos de como um intervalo de texto é ajustado para Move() e ExpandToEnclosingUnit()

O conteúdo textual (ou texto interno) de um contêiner de texto e um objeto inserido, como um hiperlink ou célula de tabela, é exposto como um só fluxo de texto contínuo na exibição de controle e na exibição de conteúdo da árvore de Automação da Interface do Usuário; os limites de objeto são ignorados. Se um cliente da Automação da Interface do Usuário estiver recuperando o texto com a finalidade de recitar, interpretar ou analisá-lo de alguma forma, o intervalo de texto deverá ser verificado para casos especiais, como uma tabela com conteúdo textual ou outros objetos inseridos. Isso pode ser feito chamando GetChildren para obter um AutomationElement para cada objeto inserido e, em seguida, chamando RangeFromChild para obter um intervalo de texto para cada elemento; isso é feito recursivamente até que todo o conteúdo textual seja recuperado.

Intervalos de texto estendidos por objetos inseridos.
Exemplo de um fluxo de texto com objetos inseridos e seus intervalos

Move respeita o texto oculto e visível. O cliente Automação da Interface do Usuário pode marcar o para visibilidade do IsHiddenAttribute texto.

Move adiará para o próximo maior TextUnit com suporte se o determinado TextUnit não tiver suporte do controle .

A ordem, da menor unidade para a maior, está listada abaixo.

Observação

O texto não é alterado de forma alguma, pois o intervalo de texto abrange apenas uma parte diferente do texto.

Aplica-se a

Confira também