![]() |
---|
本文档的目标读者是欲使用 System.Windows.Automation 命名空间中定义的托管 UI Automation类的 .NET Framework 开发人员。有关 UI Automation的最新信息,请参见 Windows Automation API: UI Automation(Windows 自动化 API:UI 自动化)。 |
本主题演示如何从 UI Automation元素检索控件模式对象。
获取所有的控件模式
获取您对其控件模式感兴趣的 AutomationElement。
调用 GetSupportedPatterns,以便从该元素获取所有控件模式。
![]() |
---|
强烈建议客户端不要使用 GetSupportedPatterns。因为该方法针对每个现有的控件模式在内部调用 GetCurrentPattern,所以性能会受到严重影响。如有可能,客户端应当针对相关的关键模式来调用 GetCurrentPattern。 |
获取特定的控件模式
获取您对其控件模式感兴趣的 AutomationElement。
调用 GetCurrentPattern 或 TryGetCurrentPattern 以查询特定模式。 这两种方法非常相似,但是,如果没有找到该模式,GetCurrentPattern 会引发异常,而 TryGetCurrentPattern 会返回 false。
示例
下面的示例检索某个列表项的 AutomationElement,并从该元素获取一个 SelectionItemPattern。
''' <summary>
''' Sets the focus to a list and selects a string item in that list.
''' </summary>
''' <param name="listElement">The list element.</param>
''' <param name="itemText">The text to select.</param>
''' <remarks>
''' This deselects any currently selected items. To add the item to the current selection
''' in a multiselect list, use AddToSelection instead of Select.
''' </remarks>
Public Sub SelectListItem(ByVal listElement As AutomationElement, ByVal itemText As String)
If listElement Is Nothing OrElse itemText = "" Then
Throw New ArgumentException("Argument cannot be null or empty.")
End If
listElement.SetFocus()
Dim cond As New PropertyCondition(AutomationElement.NameProperty, itemText, PropertyConditionFlags.IgnoreCase)
Dim elementItem As AutomationElement = listElement.FindFirst(TreeScope.Children, cond)
If Not (elementItem Is Nothing) Then
Dim pattern As SelectionItemPattern
Try
pattern = DirectCast(elementItem.GetCurrentPattern(SelectionItemPattern.Pattern), _
SelectionItemPattern)
Catch ex As InvalidOperationException
Console.WriteLine(ex.Message) ' Most likely "Pattern not supported."
Return
End Try
pattern.Select()
End If
End Sub 'SelectListItem
/// <summary>
/// Sets the focus to a list and selects a string item in that list.
/// </summary>
/// <param name="listElement">The list element.</param>
/// <param name="itemText">The text to select.</param>
/// <remarks>
/// This deselects any currently selected items. To add the item to the current selection
/// in a multiselect list, use AddToSelection instead of Select.
/// </remarks>
public void SelectListItem(AutomationElement listElement, String itemText)
{
if ((listElement == null) || (itemText == ""))
{
throw new ArgumentException("Argument cannot be null or empty.");
}
listElement.SetFocus();
Condition cond = new PropertyCondition(
AutomationElement.NameProperty, itemText, PropertyConditionFlags.IgnoreCase);
AutomationElement elementItem = listElement.FindFirst(TreeScope.Children, cond);
if (elementItem != null)
{
SelectionItemPattern pattern;
try
{
pattern = elementItem.GetCurrentPattern(SelectionItemPattern.Pattern) as SelectionItemPattern;
}
catch (InvalidOperationException ex)
{
Console.WriteLine(ex.Message); // Most likely "Pattern not supported."
return;
}
pattern.Select();
}
}