尋找清單項目的 UI 自動化項目
注意事項 |
---|
這份文件適用於想要使用 System.Windows.Automation 命名空間中定義之 Managed UI Automation 類別的 .NET Framework 開發人員。如需 UI Automation 的最新資訊,請參閱 Windows Automation API:使用者介面自動化 (英文)。 |
如何在知悉項目索引的情況下,擷取清單中項目的 AutomationElement。
範例
下列範例說明擷取清單中指定之項目的兩種方法,一種方法使用 TreeWalker,另一種方法則使用 FindAll。
第一個方法對 Win32 控制項而言較快,但第二個方法則對 Windows Presentation Foundation (WPF) 控制項來說較快。
''' <summary>
''' Retrieves an element in a list, using TreeWalker.
''' </summary>
''' <param name="parent">The list element.</param>
''' <param name="index">The index of the element to find.</param>
''' <returns>The list item.</returns>
Function FindChildAt(ByVal parent As AutomationElement, ByVal index As Integer) As AutomationElement
If (index < 0) Then
Throw New ArgumentOutOfRangeException()
End If
Dim walker As TreeWalker = TreeWalker.ControlViewWalker
Dim child As AutomationElement = walker.GetFirstChild(parent)
For x As Integer = 1 To (index - 1)
child = walker.GetNextSibling(child)
If child = Nothing Then
Throw New ArgumentOutOfRangeException()
End If
Next x
Return child
End Function
''' <summary>
''' Retrieves an element in a list, using FindAll.
''' </summary>
''' <param name="parent">The list element.</param>
''' <param name="index">The index of the element to find.</param>
''' <returns>The list item.</returns>
Function FindChildAtB(ByVal parent As AutomationElement, ByVal index As Integer) As AutomationElement
Dim findCondition As Condition = _
New PropertyCondition(AutomationElement.IsControlElementProperty, True)
Dim found As AutomationElementCollection = parent.FindAll(TreeScope.Children, findCondition)
If (index < 0) Or (index >= found.Count) Then
Throw New ArgumentOutOfRangeException()
End If
Return found(index)
End Function
/// <summary>
/// Retrieves an element in a list, using TreeWalker.
/// </summary>
/// <param name="parent">The list element.</param>
/// <param name="index">The index of the element to find.</param>
/// <returns>The list item.</returns>
AutomationElement FindChildAt(AutomationElement parent, int index)
{
if (index < 0)
{
throw new ArgumentOutOfRangeException();
}
TreeWalker walker = TreeWalker.ControlViewWalker;
AutomationElement child = walker.GetFirstChild(parent);
for (int x = 1; x <= index; x++)
{
child = walker.GetNextSibling(child);
if (child == null)
{
throw new ArgumentOutOfRangeException();
}
}
return child;
}
/// <summary>
/// Retrieves an element in a list, using FindAll.
/// </summary>
/// <param name="parent">The list element.</param>
/// <param name="index">The index of the element to find.</param>
/// <returns>The list item.</returns>
AutomationElement FindChildAtB(AutomationElement parent, int index)
{
Condition findCondition = new PropertyCondition(AutomationElement.IsControlElementProperty, true);
AutomationElementCollection found = parent.FindAll(TreeScope.Children, findCondition);
if ((index < 0) || (index >= found.Count))
{
throw new ArgumentOutOfRangeException();
}
return found[index];
}