CacheRequest 类

定义

指定在获得 AutomationElement 时,UI 自动化框架缓存的属性和模式。Specifies properties and patterns that the UI Automation framework caches when an AutomationElement is obtained.

public ref class CacheRequest sealed
public sealed class CacheRequest
type CacheRequest = class
Public NotInheritable Class CacheRequest
继承
CacheRequest

示例

下面的示例演示如何使用Activate缓存模式和属性。The following example shows how to use Activate to cache patterns and properties.

/// <summary>
/// Caches and retrieves properties for a list item by using CacheRequest.Activate.
/// </summary>
/// <param name="elementList">Element from which to retrieve a child element.</param>
/// <remarks>
/// This code demonstrates various aspects of caching. It is not intended to be 
/// an example of a useful method.
/// </remarks>
private void CachePropertiesByActivate(AutomationElement elementList)
{
    AutomationElement elementListItem;

    // Set up the request.
    CacheRequest cacheRequest = new CacheRequest();
    cacheRequest.Add(AutomationElement.NameProperty);
    cacheRequest.Add(AutomationElement.IsEnabledProperty);
    cacheRequest.Add(SelectionItemPattern.Pattern);
    cacheRequest.Add(SelectionItemPattern.SelectionContainerProperty);

    // Obtain an element and cache the requested items.
    using (cacheRequest.Activate())
    {
        Condition cond = new PropertyCondition(AutomationElement.IsSelectionItemPatternAvailableProperty, true);
        elementListItem = elementList.FindFirst(TreeScope.Children, cond);
    }
    // The CacheRequest is now inactive.

    // Retrieve the cached property and pattern.
    SelectionItemPattern pattern;
    String itemName;
    try
    {
        itemName = elementListItem.Cached.Name;
        pattern = elementListItem.GetCachedPattern(SelectionItemPattern.Pattern) as SelectionItemPattern;
    }
    catch (InvalidOperationException)
    {
        Console.WriteLine("Object was not in cache.");
        return;
    }
    // Alternatively, you can use TryGetCachedPattern to retrieve the cached pattern.
    object cachedPattern;
    if (true == elementListItem.TryGetCachedPattern(SelectionItemPattern.Pattern, out cachedPattern))
    {
        pattern = cachedPattern as SelectionItemPattern;
    }

    // Specified pattern properties are also in the cache.
    AutomationElement parentList = pattern.Cached.SelectionContainer;

    // The following line will raise an exception, because the HelpText property was not cached.
    /*** String itemHelp = elementListItem.Cached.HelpText; ***/

    // Similarly, pattern properties that were not specified in the CacheRequest cannot be 
    // retrieved from the cache. This would raise an exception.
    /*** bool selected = pattern.Cached.IsSelected; ***/

    // This is still a valid call, even though the property is in the cache.
    // Of course, the cached value and the current value are not guaranteed to be the same.
    itemName = elementListItem.Current.Name;
}
''' <summary>
''' Caches and retrieves properties for a list item by using CacheRequest.Activate.
''' </summary>
''' <param name="elementList">Element from which to retrieve a child element.</param>
''' <remarks>
''' This code demonstrates various aspects of caching. It is not intended to be 
''' an example of a useful method.
''' </remarks>
Private Sub CachePropertiesByActivate(ByVal elementList As AutomationElement)

    ' Set up the request.
    Dim myCacheRequest As New CacheRequest()
    myCacheRequest.Add(AutomationElement.NameProperty)
    myCacheRequest.Add(AutomationElement.IsEnabledProperty)
    myCacheRequest.Add(SelectionItemPattern.Pattern)
    myCacheRequest.Add(SelectionItemPattern.SelectionContainerProperty)

    Dim elementListItem As AutomationElement

    ' Obtain an element and cache the requested items.
    Using myCacheRequest.Activate()
        Dim myCondition As New PropertyCondition( _
            AutomationElement.IsSelectionItemPatternAvailableProperty, True)
        elementListItem = elementList.FindFirst(TreeScope.Children, myCondition)
    End Using


    ' The CacheRequest is now inactive.
    ' Retrieve the cached property and pattern.
    Dim pattern As SelectionItemPattern
    Dim itemName As String
    Try
        itemName = elementListItem.Cached.Name
        pattern = DirectCast(elementListItem.GetCachedPattern(SelectionItemPattern.Pattern), _
            SelectionItemPattern)
    Catch ex As InvalidOperationException
        Console.WriteLine("Object was not in cache.")
        Return
    End Try
    ' Alternatively, you can use TryGetCachedPattern to retrieve the cached pattern.
    Dim cachedPattern As Object = Nothing
    If True = elementListItem.TryGetCachedPattern(SelectionItemPattern.Pattern, cachedPattern) Then
        pattern = DirectCast(cachedPattern, SelectionItemPattern)
    End If

    ' Specified pattern properties are also in the cache.
    Dim parentList As AutomationElement = pattern.Cached.SelectionContainer

    ' The following line will raise an exception, because the HelpText property was not cached.
    '** String itemHelp = elementListItem.Cached.HelpText; **

    ' Similarly, pattern properties that were not specified in the CacheRequest cannot be 
    ' retrieved from the cache. This would raise an exception.
    '** bool selected = pattern.Cached.IsSelected; **

    ' This is still a valid call, even though the property is in the cache.
    ' Of course, the cached value and the current value are not guaranteed to be the same.
    itemName = elementListItem.Current.Name
End Sub

下面的示例演示如何使用PushPop来缓存模式和属性。The following example shows how to use Push and Pop to cache patterns and properties.

/// <summary>
/// Caches and retrieves properties for a list item by using CacheRequest.Push.
/// </summary>
/// <param name="autoElement">Element from which to retrieve a child element.</param>
/// <remarks>
/// This code demonstrates various aspects of caching. It is not intended to be 
/// an example of a useful method.
/// </remarks>
private void CachePropertiesByPush(AutomationElement elementList)
{
    // Set up the request.
    CacheRequest cacheRequest = new CacheRequest();

    // Do not get a full reference to the cached objects, only to their cached properties and patterns.
    cacheRequest.AutomationElementMode = AutomationElementMode.None;

    // Cache all elements, regardless of whether they are control or content elements.
    cacheRequest.TreeFilter = Automation.RawViewCondition;

    // Property and pattern to cache.
    cacheRequest.Add(AutomationElement.NameProperty);
    cacheRequest.Add(SelectionItemPattern.Pattern);

    // Activate the request.
    cacheRequest.Push();

    // Obtain an element and cache the requested items.
    Condition cond = new PropertyCondition(AutomationElement.IsSelectionItemPatternAvailableProperty, true);
    AutomationElement elementListItem = elementList.FindFirst(TreeScope.Children, cond);

    // At this point, you could call another method that creates a CacheRequest and calls Push/Pop.
    // While that method was retrieving automation elements, the CacheRequest set in this method 
    // would not be active. 

    // Deactivate the request.
    cacheRequest.Pop();

    // Retrieve the cached property and pattern.
    String itemName = elementListItem.Cached.Name;
    SelectionItemPattern pattern = elementListItem.GetCachedPattern(SelectionItemPattern.Pattern) as SelectionItemPattern;

    // The following is an alternative way of retrieving the Name property.
    itemName = elementListItem.GetCachedPropertyValue(AutomationElement.NameProperty) as String;

    // This is yet another way, which returns AutomationElement.NotSupported if the element does
    // not supply a value. If the second parameter is false, a default name is returned.
    object objName = elementListItem.GetCachedPropertyValue(AutomationElement.NameProperty, true);
    if (objName == AutomationElement.NotSupported)
    {
        itemName = "Unknown";
    }
    else
    {
        itemName = objName as String;
    }

    // The following call raises an exception, because only the cached properties are available, 
    //  as specified by cacheRequest.AutomationElementMode. If AutomationElementMode had its
    //  default value (Full), this call would be valid.
    /*** bool enabled = elementListItem.Current.IsEnabled; ***/
}
''' <summary>
''' Caches and retrieves properties for a list item by using CacheRequest.Push.
''' </summary>
''' <param name="elementList">Element from which to retrieve a child element.</param>
''' <remarks>
''' This code demonstrates various aspects of caching. It is not intended to be 
''' an example of a useful method.
''' </remarks>
Private Sub CachePropertiesByPush(ByVal elementList As AutomationElement)
    ' Set up the request.
    Dim cacheRequest As New CacheRequest()

    ' Do not get a full reference to the cached objects, only to their cached properties and patterns.
    cacheRequest.AutomationElementMode = AutomationElementMode.None

    ' Cache all elements, regardless of whether they are control or content elements.
    cacheRequest.TreeFilter = Automation.RawViewCondition

    ' Property and pattern to cache.
    cacheRequest.Add(AutomationElement.NameProperty)
    cacheRequest.Add(SelectionItemPattern.Pattern)

    ' Activate the request.
    cacheRequest.Push()

    ' Obtain an element and cache the requested items.
    Dim myCondition As New PropertyCondition(AutomationElement.IsSelectionItemPatternAvailableProperty, _
        True)
    Dim elementListItem As AutomationElement = elementList.FindFirst(TreeScope.Children, myCondition)

    ' At this point, you could call another method that creates a CacheRequest and calls Push/Pop.
    ' While that method was retrieving automation elements, the CacheRequest set in this method 
    ' would not be active. 
    ' Deactivate the request.
    cacheRequest.Pop()

    ' Retrieve the cached property and pattern.
    Dim itemName As String = elementListItem.Cached.Name
    Dim pattern As SelectionItemPattern = _
        DirectCast(elementListItem.GetCachedPattern(SelectionItemPattern.Pattern), SelectionItemPattern)

    ' The following is an alternative way of retrieving the Name property.
    itemName = CStr(elementListItem.GetCachedPropertyValue(AutomationElement.NameProperty))

    ' This is yet another way, which returns AutomationElement.NotSupported if the element does
    ' not supply a value. If the second parameter is false, a default name is returned.
    Dim objName As Object = elementListItem.GetCachedPropertyValue(AutomationElement.NameProperty, True)
    If objName Is AutomationElement.NotSupported Then
        itemName = "Unknown"
    Else
        itemName = CStr(objName)
    End If
    ' The following call raises an exception, because only the cached properties are available, 
    '  as specified by cacheRequest.AutomationElementMode. If AutomationElementMode had its
    '  default value (Full), this call would be valid.
    '** bool enabled = elementListItem.Current.IsEnabled; **

End Sub

注解

通过UI 自动化UI Automation检索属性和模式需要跨进程调用, 从而降低性能。Retrieving properties and patterns through UI 自动化UI Automation requires cross-process calls that can slow down performance. 通过在批处理操作中缓存 microsoft.support 和模式的值, 你可以提高应用程序的性能。By caching values of proprieties and patterns in a batch operation, you can enhance the performance of your application.

通过调用类构造函数来创建新的缓存请求。Create a new cache request by calling the class constructor. 该请求通过对Add方法的重复调用来填充。The request is populated by repeated calls to the Add method.

只有一个可以处于活动状态。 CacheRequestOnly a single CacheRequest can be active. 可以通过两种方式激活请求:There are two ways to activate a request:

  • 请求Activate上调用。Call Activate on the request. 这会将请求推送到堆栈上, 并在释放对象时弹出请求。This pushes the request onto the stack, and the request is popped when the object is disposed. 若要确保即使引发异常也能进行处理, 请使用Activate using块中的返回值 (Using在 Visual Basic 中)。To ensure disposal even if an exception is raised, use the return value from Activate within a using block (Using in Visual Basic).

  • 通过调用Push将请求放到内部堆栈上。Put the request onto the internal stack by calling Push. 堆栈上只有最顶层的请求处于活动状态, 并且必须是从堆栈Pop中移除的下一个请求。Only the topmost request on the stack is active, and it must be the next one removed from the stack by Pop. 弹出请求会将其停用。Popping the request deactivates it.

UI 自动化UI Automation请求处于活动状态时获得的元素将为指定的属性和模式使用缓存值。elements obtained while the request is active will have cached values for the properties and patterns specified.

构造函数

CacheRequest()

初始化 CacheRequest 类的新实例。Initializes a new instance of the CacheRequest class.

属性

AutomationElementMode

获取或设置一个值,该值指定返回的元素是应包含对基础 用户界面 (UI)user interface (UI) 的完整引用,还是仅包含缓存的信息。Gets or sets a value that specifies whether returned elements should contain full references to the underlying 用户界面 (UI)user interface (UI), or only cached information.

Current

获取当前线程中处于活动状态的 CacheRequestGets the CacheRequest that is active on the current thread.

TreeFilter

获取或设置一个值,该值指定缓存时要使用的 UI 自动化UI Automation 元素树的视图。Gets or sets a value specifying the view of the UI 自动化UI Automation element tree to use when caching.

TreeScope

获取或设置一个值,该值指定是仅对子树的根进行缓存,还是也对其子级或子代进行缓存。Gets or sets a value that specifies whether caching is done only for the root of the subtree, or also for its children or descendants.

方法

Activate()

将此 CacheRequest 设置为在同一线程中请求 AutomationElement 时返回的项的活动规范。Sets this CacheRequest as the active specification for the items that are returned when an AutomationElement is requested on the same thread.

Add(AutomationPattern)

将指定的 AutomationPattern 标识符添加到此 CacheRequestAdds the specified AutomationPattern identifier to this CacheRequest.

Add(AutomationProperty)

将指定的 AutomationProperty 标识符添加到此 CacheRequestAdds the specified AutomationProperty identifier to this CacheRequest.

Clone()

创建此 CacheRequest 的副本。Creates a copy of this CacheRequest.

Equals(Object)

确定指定对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(继承自 Object)
GetHashCode()

用作默认哈希函数。Serves as the default hash function.

(继承自 Object)
GetType()

获取当前实例的 TypeGets the Type of the current instance.

(继承自 Object)
MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(继承自 Object)
Pop()

从当前线程的内部堆栈中移除活动的 CacheRequestRemoves the active CacheRequest from the internal stack for the current thread.

Push()

CacheRequest 压入内部状态堆栈,并使它成为当前线程中的活动请求。Places the CacheRequest on the internal state stack, making it the active request on the current thread.

ToString()

返回表示当前对象的字符串。Returns a string that represents the current object.

(继承自 Object)

适用于

另请参阅