CacheRequest CacheRequest CacheRequest CacheRequest Class

Definizione

Specifica proprietà e pattern che il framework di automazione interfaccia utente memorizza nella cache quando viene ottenuto un oggetto AutomationElement.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
Ereditarietà
CacheRequestCacheRequestCacheRequestCacheRequest

Esempi

Nell'esempio seguente viene illustrato come utilizzare Activate per memorizzare nella cache modelli e proprietà.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

Nell'esempio seguente viene illustrato come utilizzare Push e Pop per memorizzare nella cache modelli e proprietà.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

Commenti

Il recupero di proprietà e modelli Automazione interfaccia utenteUI Automation tramite richiede chiamate tra processi che possono rallentare le prestazioni.Retrieving properties and patterns through Automazione interfaccia utenteUI Automation requires cross-process calls that can slow down performance. Memorizzando nella cache i valori delle relative caratteristiche e dei modelli in un'operazione batch, è possibile migliorare le prestazioni dell'applicazione.By caching values of proprieties and patterns in a batch operation, you can enhance the performance of your application.

Creare una nuova richiesta di cache chiamando il costruttore della classe.Create a new cache request by calling the class constructor. La richiesta viene popolata da chiamate ripetute Add al metodo.The request is populated by repeated calls to the Add method.

Può essere attivo CacheRequest solo un singolo.Only a single CacheRequest can be active. È possibile attivare una richiesta in due modi:There are two ways to activate a request:

  • Chiamare Activate sulla richiesta.Call Activate on the request. Questa operazione esegue il push della richiesta nello stack e la richiesta viene spuntata quando l'oggetto viene eliminato.This pushes the request onto the stack, and the request is popped when the object is disposed. Per garantire l'eliminazione anche se viene generata un'eccezione, usare il valore restituito Activate dall'interno using di unUsing blocco (in 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).

  • Inserire la richiesta nello stack interno chiamando Push.Put the request onto the internal stack by calling Push. Solo la richiesta più in alto nello stack è attiva e deve essere quella successiva rimossa dallo stack da Pop.Only the topmost request on the stack is active, and it must be the next one removed from the stack by Pop. La richiesta viene disattivata.Popping the request deactivates it.

Automazione interfaccia utenteUI Automationgli elementi ottenuti mentre la richiesta è attiva avranno valori memorizzati nella cache per le proprietà e i criteri specificati.elements obtained while the request is active will have cached values for the properties and patterns specified.

Costruttori

CacheRequest() CacheRequest() CacheRequest() CacheRequest()

Inizializza una nuova istanza della classe CacheRequest.Initializes a new instance of the CacheRequest class.

Proprietà

AutomationElementMode AutomationElementMode AutomationElementMode AutomationElementMode

Ottiene o imposta un valore che specifica se gli elementi restituiti devono contenere riferimenti completi alla interfaccia utenteuser interface (UI) sottostante, o solo le informazioni memorizzate nella cache.Gets or sets a value that specifies whether returned elements should contain full references to the underlying interfaccia utenteuser interface (UI), or only cached information.

Current Current Current Current

Ottiene l'oggetto CacheRequest attivo sul thread corrente.Gets the CacheRequest that is active on the current thread.

TreeFilter TreeFilter TreeFilter TreeFilter

Ottiene o imposta un valore che specifica la visualizzazione dell'albero degli elementi di Automazione interfaccia utenteUI Automation da usare durante la memorizzazione nella cache.Gets or sets a value specifying the view of the Automazione interfaccia utenteUI Automation element tree to use when caching.

TreeScope TreeScope TreeScope TreeScope

Ottiene o imposta un valore che specifica se la memorizzazione nella cache viene effettuata solo per la radice del sottoalbero, o anche per gli oggetti figlio o discendenti.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.

Metodi

Activate() Activate() Activate() Activate()

Imposta questo oggetto CacheRequest come specifica attiva per gli elementi restituiti quando viene richiesto un oggetto AutomationElement sullo stesso thread.Sets this CacheRequest as the active specification for the items that are returned when an AutomationElement is requested on the same thread.

Add(AutomationPattern) Add(AutomationPattern) Add(AutomationPattern) Add(AutomationPattern)

Aggiunge a questo oggetto AutomationPattern l'identificatore CacheRequest specificato.Adds the specified AutomationPattern identifier to this CacheRequest.

Add(AutomationProperty) Add(AutomationProperty) Add(AutomationProperty) Add(AutomationProperty)

Aggiunge a questo oggetto AutomationProperty l'identificatore CacheRequest specificato.Adds the specified AutomationProperty identifier to this CacheRequest.

Clone() Clone() Clone() Clone()

Crea una copia dell'oggetto CacheRequest.Creates a copy of this CacheRequest.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

Determina se l'oggetto specificato è uguale all'oggetto corrente.Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

Funge da funzione hash predefinita.Serves as the default hash function.

(Inherited from Object)
GetType() GetType() GetType() GetType()

Ottiene l'oggetto Type dell'istanza corrente.Gets the Type of the current instance.

(Inherited from Object)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

Crea una copia superficiale dell'oggetto Object corrente.Creates a shallow copy of the current Object.

(Inherited from Object)
Pop() Pop() Pop() Pop()

Rimuove l'oggetto CacheRequest attivo dallo stack interno per il thread corrente.Removes the active CacheRequest from the internal stack for the current thread.

Push() Push() Push() Push()

Colloca l'oggetto CacheRequest nello stack di stato interno, rendendolo richiesta attiva nel thread corrente.Places the CacheRequest on the internal state stack, making it the active request on the current thread.

ToString() ToString() ToString() ToString()

Restituisce una stringa che rappresenta l'oggetto corrente.Returns a string that represents the current object.

(Inherited from Object)

Si applica a

Vedi anche