다음을 통해 공유


AutomationID 속성 사용

비고

이 설명서는 네임스페이스에 정의된 관리되는 UI 자동화 클래스를 사용하려는 .NET Framework 개발자를 System.Windows.Automation 위한 것입니다. UI 자동화에 대한 최신 정보는 Windows Automation API: UI 자동화를 참조하세요.

이 항목에는 UI 자동화 트리 내에서 요소를 찾는 데 사용할 수 있는 방법과 시기를 AutomationIdProperty 보여 주는 시나리오 및 샘플 코드가 포함되어 있습니다.

AutomationIdProperty는 UI 자동화 요소를 형제 요소 중에서 고유하게 식별합니다. 컨트롤 식별과 관련된 속성 식별자에 대한 자세한 내용은 UI 자동화 속성 개요를 참조하세요.

비고

AutomationIdProperty 는 트리 전체에서 고유한 ID를 보장하지 않습니다. 일반적으로 컨테이너 및 범위 정보가 유용해야 합니다. 애플리케이션에 여러 최상위 메뉴 항목과 이러한 항목 각각에 여러 하위 메뉴 항목이 있는 메뉴 컨트롤이 포함될 수 있습니다. 이러한 보조 메뉴 항목은 "Item1", "Item 2" 등과 같은 제네릭 구성표로 식별될 수 있으므로 최상위 메뉴 항목에서 자식에 대한 중복 식별자를 허용합니다.

시나리오

요소를 검색할 때 정확하고 일관된 결과를 얻기 위해 사용해야 AutomationIdProperty 하는 세 가지 기본 UI 자동화 클라이언트 애플리케이션 시나리오가 식별되었습니다.

비고

AutomationIdProperty 는 최상위 애플리케이션 창, ID 또는 x:Uid가 없는 WPF(Windows Presentation Foundation) 컨트롤에서 파생된 UI 자동화 요소, 컨트롤 ID가 없는 Win32 컨트롤에서 파생된 UI 자동화 요소를 제외한 컨트롤 뷰의 모든 UI 자동화 요소에서 지원됩니다.

고유하고 검색 가능한 AutomationID를 사용하여 UI 자동화 트리에서 특정 요소 찾기

  • UI Spy와 같은 도구를 사용하여 관심 있는 UI 요소의 특정 속성 AutomationIdProperty을(를) 보고합니다. 그런 다음 이 값을 복사하여 후속 자동화된 테스트를 위한 테스트 스크립트와 같은 클라이언트 애플리케이션에 붙여넣을 수 있습니다. 이 방법은 런타임에 요소를 식별하고 찾는 데 필요한 코드를 줄이고 간소화합니다.

주의

일반적으로는 RootElement 요소의 직접 자식만 가져오려고 합니다. 하위 항목에 대한 검색은 수백 또는 수천 개의 요소를 반복하여 스택 오버플로가 발생할 수 있습니다. 하위 수준에서 특정 요소를 가져오려는 경우 애플리케이션 창 또는 낮은 수준의 컨테이너에서 검색을 시작해야 합니다.

///--------------------------------------------------------------------
/// <summary>
/// Finds all elements in the UI Automation tree that have a specified
/// AutomationID.
/// </summary>
/// <param name="targetApp">
/// The root element from which to start searching.
/// </param>
/// <param name="automationID">
/// The AutomationID value of interest.
/// </param>
/// <returns>
/// The collection of UI Automation elements that have the specified
/// AutomationID value.
/// </returns>
///--------------------------------------------------------------------
private AutomationElementCollection FindElementFromAutomationID(AutomationElement targetApp,
    string automationID)
{
    return targetApp.FindAll(
        TreeScope.Descendants,
        new PropertyCondition(AutomationElement.AutomationIdProperty, automationID));
}
'''--------------------------------------------------------------------
''' <summary>
''' Finds all elements in the UI Automation tree that have a specified
''' AutomationID.
''' </summary>
''' <param name="targetApp">
''' The root element from which to start searching.
''' </param>
''' <param name="automationID">
''' The AutomationID value of interest.
''' </param>
''' <returns>
''' The collection of automation elements that have the specified
''' AutomationID value.
''' </returns>
'''--------------------------------------------------------------------
Private Function FindElementFromAutomationID( _
ByVal targetApp As AutomationElement, _
ByVal automationID As String) As AutomationElementCollection
    Return targetApp.FindAll( _
    TreeScope.Descendants, _
    New PropertyCondition( _
    AutomationElement.AutomationIdProperty, automationID))
End Function 'FindElementFromAutomationID

영구 경로를 사용하여 이전에 식별된 AutomationElement로 돌아갑니다.

  • 간단한 테스트 스크립트에서 강력한 레코드 및 재생 유틸리티에 이르기까지 클라이언트 애플리케이션은 파일 열기 대화 상자 또는 메뉴 항목과 같이 현재 인스턴스화되지 않은 요소에 액세스해야 하므로 UI 자동화 트리에 존재하지 않을 수 있습니다. 이러한 요소는 AutomationID, 컨트롤 패턴 및 이벤트 수신기와 같은 UI 자동화 속성을 사용하여 특정 UI 동작 시퀀스를 재현하거나 "재생"해야만 인스턴스화할 수 있습니다.
///--------------------------------------------------------------------
/// <summary>
/// Creates a UI Automation thread.
/// </summary>
/// <param name="sender">Object that raised the event.</param>
/// <param name="e">Event arguments.</param>
/// <remarks>
/// UI Automation must be called on a separate thread if the client
/// application itself could become a target for event handling.
/// For example, focus tracking is a desktop event that could involve
/// the client application.
/// </remarks>
///--------------------------------------------------------------------
private void CreateUIAThread(object sender, EventArgs e)
{
    // Start another thread to do the UI Automation work.
    ThreadStart threadDelegate = new ThreadStart(CreateUIAWorker);
    Thread workerThread = new Thread(threadDelegate);
    workerThread.Start();
}

///--------------------------------------------------------------------
/// <summary>
/// Delegated method for ThreadStart. Creates a UI Automation worker
/// class that does all UI Automation related work.
/// </summary>
///--------------------------------------------------------------------
public void CreateUIAWorker()
{
   uiautoWorker = new FindByAutomationID(targetApp);
}
private FindByAutomationID uiautoWorker;

'''--------------------------------------------------------------------
''' <summary>
''' Creates a UI Automation thread.
''' </summary>
''' <param name="sender">Object that raised the event.</param>
''' <param name="e">Event arguments.</param>
''' <remarks>
''' UI Automation must be called on a separate thread if the client
''' application itself could become a target for event handling.
''' For example, focus tracking is a desktop event that could involve
''' the client application.
''' </remarks>
'''--------------------------------------------------------------------
Private Sub CreateUIAThread(ByVal sender As Object, ByVal e As EventArgs)

    ' Start another thread to do the UI Automation work.
    Dim threadDelegate As New ThreadStart(AddressOf CreateUIAWorker)
    Dim workerThread As New Thread(threadDelegate)
    workerThread.Start()

End Sub


'''--------------------------------------------------------------------
''' <summary>
''' Delegated method for ThreadStart. Creates a UI Automation worker
''' class that does all UI Automation related work.
''' </summary>
'''--------------------------------------------------------------------
Public Sub CreateUIAWorker()

    uiautoWorker = New UIAWorker(targetApp)

End Sub

Private uiautoWorker As UIAWorker

///--------------------------------------------------------------------
/// <summary>
/// Function to playback through a series of recorded events calling
/// a WriteToScript function for each event of interest.
/// </summary>
/// <remarks>
/// A major drawback to using AutomationID for recording user
/// interactions in a volatile UI is the probability of catastrophic
/// change in the UI. For example, the //Processes// dialog where items
/// in the listbox container can change with no input from the user.
/// This mandates that a record and playback application must be
/// reliant on the tester owning the UI being tested. In other words,
/// there has to be a contract between the provider and client that
/// excludes uncontrolled, external applications. The added benefit
/// is the guarantee that each control in the UI should have an
/// AutomationID assigned to it.
///
/// This function relies on a UI Automation worker class to create
/// the System.Collections.Generic.Queue object that stores the
/// information for the recorded user interactions. This
/// allows post-processing of the recorded items prior to actually
/// writing them to a script. If this is not necessary the interaction
/// could be written to the script immediately.
/// </remarks>
///--------------------------------------------------------------------
private void Playback(AutomationElement targetApp)
{
    AutomationElement element;
    foreach(ElementStore storedItem in uiautoWorker.elementQueue)
    {
        PropertyCondition propertyCondition =
            new PropertyCondition(
            AutomationElement.AutomationIdProperty, storedItem.AutomationID);
        // Confirm the existence of a control.
        // Depending on the controls and complexity of interaction
        // this step may not be necessary or may require additional
        // functionality. For example, to confirm the existence of a
        // child menu item that had been invoked the parent menu item
        // would have to be expanded.
        element = targetApp.FindFirst(TreeScope.Descendants, propertyCondition);
        if(element == null)
        {
            // Control not available, unable to continue.
            // TODO: Handle error condition.
            return;
        }
        WriteToScript(storedItem.AutomationID, storedItem.EventID);
    }
}

///--------------------------------------------------------------------
/// <summary>
/// Generates script code and outputs the code to a text control in
/// the client.
/// </summary>
/// <param name="automationID">
/// The AutomationID of the current control.
/// </param>
/// <param name="eventID">
/// The event recorded on that control.
/// </param>
///--------------------------------------------------------------------
private void WriteToScript(string automationID, string eventID)
{
    // Script code would be generated and written to an output file
    // as plain text at this point, but for the
    // purposes of this example we just write to the console.
    Console.WriteLine(automationID + " - " + eventID);
}
'''--------------------------------------------------------------------
''' <summary>
''' Function to playback through a series of recorded events calling
''' a WriteToScript function for each event of interest.
''' </summary>
''' <remarks>
''' A major drawback to using AutomationID for recording user
''' interactions in a volatile UI is the probability of catastrophic
''' change in the UI. For example, the 'Processes' dialog where items
''' in the listbox container can change with no input from the user.
''' This mandates that a record and playback application must be
''' reliant on the tester owning the UI being tested. In other words,
''' there has to be a contract between the provider and client that
''' excludes uncontrolled, external applications. The added benefit
''' is the guarantee that each control in the UI should have an
''' AutomationID assigned to it.
'''
''' This function relies on a UI Automation worker class to create
''' the System.Collections.Generic.Queue object that stores the
''' information for the recorded user interactions. This
''' allows post-processing of the recorded items prior to actually
''' writing them to a script. If this is not necessary the interaction
''' could be written to the script immediately.
''' </remarks>
'''--------------------------------------------------------------------
Private Sub Playback(ByVal targetApp As AutomationElement)

    Dim element As AutomationElement
    Dim storedItem As ElementStore
    For Each storedItem In uiautoWorker.elementQueue
        Dim propertyCondition As New PropertyCondition( _
        AutomationElement.AutomationIdProperty, storedItem.AutomationID)
        ' Confirm the existence of a control.
        ' Depending on the controls and complexity of interaction
        ' this step may not be necessary or may require additional
        ' functionality. For example, to confirm the existence of a
        ' child menu item that had been invoked the parent menu item
        ' would have to be expanded.
        element = targetApp.FindFirst( _
        TreeScope.Descendants, propertyCondition)
        If element Is Nothing Then
            ' Control not available, unable to continue.
            ' TODO: Handle error condition.
            Return
        End If
        WriteToScript(storedItem.AutomationID, storedItem.EventID)
    Next storedItem

End Sub


'''--------------------------------------------------------------------
''' <summary>
''' Generates script code and outputs the code to a text control in
''' the client.
''' </summary>
''' <param name="automationID">
''' The AutomationID of the current control.
''' </param>
''' <param name="eventID">
''' The event recorded on that control.
''' </param>
'''--------------------------------------------------------------------
Private Sub WriteToScript( _
ByVal automationID As String, ByVal eventID As String)

    ' Script code would be generated and written to an output file
    ' as plain text at this point, but for the
    ' purposes of this example we just write to the console.
    Console.WriteLine(automationID + " - " + eventID)

End Sub

상대 경로를 사용하여 이전에 식별된 AutomationElement로 돌아갑니다.

  • 특정 상황에서 AutomationID는 형제 간에만 고유하도록 보장되므로 UI 자동화 트리의 여러 요소에 동일한 AutomationID 속성 값이 있을 수 있습니다. 이러한 상황에서는 부모 및 필요한 경우 조부모를 기반으로 요소를 고유하게 식별할 수 있습니다. 예를 들어 개발자는 "Item1", "Item2" 등과 같은 순차적 AutomationID로 자식이 식별되는 여러 자식 메뉴 항목이 있는 여러 메뉴 항목이 있는 메뉴 모음을 제공할 수 있습니다. 그런 다음 각 메뉴 항목을 해당 부모의 AutomationID 및 필요한 경우 해당 조부모와 함께 AutomationID로 고유하게 식별할 수 있습니다.

참고하십시오