Compartir a través de


Obtener detalles de atributos de texto diversos mediante UI Automation

NotaNota

Esta documentación está dirigida a desarrolladores de .NET Framework que desean usar las clases administradas de UI Automation definidas en el espacio de nombres System.Windows.Automation.Para obtener información actualizada sobre UI Automation, vea Windows Automation API: UI Automation.

En este tema se muestra cómo utilizar la Microsoft UI Automation para obtener detalles de atributos de texto de un intervalo de texto que abarca varios valores de atributo. Un intervalo de texto puede corresponderse con la ubicación actual del símbolo de intercalación (o selección degenerada) en un documento, una selección contigua de texto, una colección de selecciones de texto no relacionadas o el contenido textual completo de un documento.

Ejemplo

En el ejemplo de código siguiente se muestra cómo obtener FontNameAttribute de un intervalo de texto donde GetAttributeValue devuelve un objeto MixedAttributeValue.

'--------------------------------------------------------------------
' <summary>
' Display the target selection with attribute details in client.
' </summary>
' <param name="selectedText">The current target selection.</param>
'--------------------------------------------------------------------
Private Sub DisplaySelectedTextWithAttributes(ByVal selectedText As String)
    targetSelection.Text = selectedText
    ' We're only interested in the FontNameAttribute for the purposes 
    ' of this sample.
    targetSelectionAttributes.Text = _
        ParseTextRangeByAttribute( _
        selectedText, TextPattern.FontNameAttribute)
End Sub

'--------------------------------------------------------------------
' <summary>
' Parse the target selection based on the text attribute of interest.
' </summary>
' <param name="selectedText">The current target selection.</param>
' <param name="automationTextAttribute">
' The text attribute of interest.
' </param>
' <returns>
' A string representing the requested attribute details.
' </returns>
'--------------------------------------------------------------------
Function ParseTextRangeByAttribute( _
ByVal selectedText As String, _
ByVal automationTextAttribute As AutomationTextAttribute) As String
    Dim attributeDetails As StringBuilder = New StringBuilder()
    ' Initialize the current attribute value.
    Dim attributeValue As String = ""
    ' Make a copy of the text range.
    Dim searchRangeClone As TextPatternRange = searchRange.Clone()
    ' Collapse the range to the starting endpoint.
    searchRangeClone.Move(TextUnit.Character, -1)
    ' Iterate through the range character by character.
    Dim x As Integer
    For x = 1 To selectedText.Length
        searchRangeClone.Move(TextUnit.Character, 1)
        ' Get the attribute value of the current character.
        Dim newAttributeValue As String = _
            searchRangeClone.GetAttributeValue(automationTextAttribute).ToString()
        ' If the new attribute value is not equal to the old then report 
        ' the new value along with its ___location within the range.
        If (newAttributeValue <> attributeValue) Then
            attributeDetails.Append(automationTextAttribute.ProgrammaticName) _
            .Append(":") _
            .Append(vbLf) _
            .Append("<") _
            .Append(newAttributeValue) _
            .Append("> at text range position ") _
            .AppendLine(x.ToString())
            attributeValue = newAttributeValue
        End If
    Next
    Return attributeDetails.ToString()
End Function
///--------------------------------------------------------------------
/// <summary>
/// Display the target selection with attribute details in client.
/// </summary>
/// <param name="selectedText">The current target selection.</param>
///--------------------------------------------------------------------
private void DisplaySelectedTextWithAttributes(string selectedText)
{
    targetSelection.Text = selectedText;
    // We're only interested in the FontNameAttribute for the purposes 
    // of this sample.
    targetSelectionAttributes.Text = 
        ParseTextRangeByAttribute(
        selectedText, TextPattern.FontNameAttribute);
}

///--------------------------------------------------------------------
/// <summary>
/// Parse the target selection based on the text attribute of interest.
/// </summary>
/// <param name="selectedText">The current target selection.</param>
/// <param name="automationTextAttribute">
/// The text attribute of interest.
/// </param>
/// <returns>
/// A string representing the requested attribute details.
/// </returns>
///--------------------------------------------------------------------
private string ParseTextRangeByAttribute(
    string selectedText, 
    AutomationTextAttribute automationTextAttribute)
{
    StringBuilder attributeDetails = new StringBuilder();
    // Initialize the current attribute value.
    string attributeValue = "";
    // Make a copy of the text range.
    TextPatternRange searchRangeClone = searchRange.Clone();
    // Collapse the range to the starting endpoint.
    searchRangeClone.Move(TextUnit.Character, -1);
    // Iterate through the range character by character.
    for (int x = 1; x <= selectedText.Length; x++)
    {
        searchRangeClone.Move(TextUnit.Character, 1);
        // Get the attribute value of the current character.
        string newAttributeValue = 
            searchRangeClone.GetAttributeValue(automationTextAttribute).ToString();
        // If the new attribute value is not equal to the old then report 
        // the new value along with its ___location within the range.
        if (newAttributeValue != attributeValue)
        {
            attributeDetails.Append(automationTextAttribute.ProgrammaticName)
                .Append(":\n<")
                .Append(newAttributeValue)
                .Append("> at text range position ")
                .AppendLine(x.ToString());
            attributeValue = newAttributeValue;
        }
    }
    return attributeDetails.ToString();
}

El patrón de control de TextPattern, junto con la clase TextPatternRange, admite atributos, propiedades y métodos de texto básicos. Para funcionalidad específica de controles no compatible con TextPattern o TextPatternRange, la clase AutomationElement proporciona métodos para que un cliente de Automatización de la interfaz de usuario obtenga acceso al modelo de objetos nativo correspondiente.

Vea también

Tareas

Agregar contenido a un cuadro de texto utilizando la UI Automation

Buscar y resaltar texto mediante UI Automation

Obtener atributos de texto mediante UI Automation

Conceptos

Información general sobre el modelo de texto de UI Automation

Información general acerca de los patrones de control de automatización de la interfaz de usuario

Patrones de controles de UI Automation para clientes