Muokkaa

Jaa


Get the Toggle State of a Check Box Using UI Automation

Note

This documentation is intended for .NET Framework developers who want to use the managed UI Automation classes defined in the System.Windows.Automation namespace. For the latest information about UI Automation, see Windows Automation API: UI Automation.

This topic shows how to use Microsoft UI Automation to get the toggle state of a control.

Example

This example uses the GetCurrentPattern method of the AutomationElement class to obtain a TogglePattern object from a control and return its ToggleState property.

/// <summary>
/// Gets the toggle state of an element in the target application.
/// </summary>
/// <param name="element">The target element.</param>
private bool IsElementToggledOn(AutomationElement element)
{
    if (element == null)
    {
        // TODO: Invalid parameter error handling.
        return false;
    }

    Object objPattern;
    TogglePattern togPattern;
    if (true == element.TryGetCurrentPattern(TogglePattern.Pattern, out objPattern))
    {
        togPattern = objPattern as TogglePattern;
        return togPattern.Current.ToggleState == ToggleState.On;
    }
    // TODO: Object doesn't support TogglePattern error handling.
    return false;
}
''' <summary>
''' Gets the toggle state of an element in the target application.
''' </summary>
''' <param name="element">The target element.</param>
Private Function IsElementToggledOn(ByVal element As AutomationElement) As Boolean
    If element Is Nothing Then
        ' TODO: Invalid parameter error handling.
        Return False
    End If

    Dim objPattern As Object = Nothing
    Dim togPattern As TogglePattern
    If True = element.TryGetCurrentPattern(TogglePattern.Pattern, objPattern) Then
        togPattern = TryCast(objPattern, TogglePattern)
        Return togPattern.Current.ToggleState = ToggleState.On
    End If
    ' TODO: Object doesn't support TogglePattern error handling.
    Return False
End Function