使用 UI 自動化取得核取方塊的切換狀態Get the Toggle State of a Check Box Using UI Automation

注意

這份文件適用於想要使用 System.Windows.Automation 命名空間中定義之 Managed UI 自動化UI Automation 類別的 .NET Framework 開發人員。This documentation is intended for .NET Framework developers who want to use the managed UI 自動化UI Automation classes defined in the System.Windows.Automation namespace. 如需的最新UI 自動化UI Automation資訊, 請參閱 Windows Automation API:使用者介面自動化。For the latest information about UI 自動化UI Automation, see Windows Automation API: UI Automation.

本主題說明如何使用Microsoft UI 自動化Microsoft UI Automation來取得控制項的切換狀態。This topic shows how to use Microsoft UI 自動化Microsoft UI Automation to get the toggle state of a control.

範例Example

這個範例會使用GetCurrentPattern AutomationElement類別的方法, 從控制項取得TogglePattern物件, 並傳回其ToggleState屬性。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