마. 실습: 포커스 트레커

이제 UI 자동화 기술을 이용하는 첫 번째 프로그램인 포커스 트래커를 만들어 봅시다. 포커스 트래커는 포커스가 바뀔 때마다 포커스를 소유한 UI 자동화 요소의 정보를 출력하는 프로그램입니다.

[그림 2.1] 포커스 트래커 실행 화면
[그림 2.1] 포커스 트래커 실행 화면

 먼저 C#언어를 사용하는 콘솔 응용 프로그램 프로젝트를 생성하세요. 그리고 포커스 트래커를 만들기 위해 필요한 UI 자동화 기술 요소를 참조합시다. 여기에서는 UI 자동화 클라이언트와 UI 자동화 타입에 관한 어셈블리가 필요합니다.

[그림 2.2] 포커스 트래커에 필요한 어셈블리 참조
[그림 2.2] 포커스 트래커에 필요한 어셈블리 참조

포커스가 바뀌는 것을 감지하였을 때 처리하기 위한 이벤트 핸들러 형식은 UI 자동화 클라이언트 어셈블리에 AutomationFocusChangedEventhandler 이름으로 만들어져 있습니다.

public delegate void AutomationFocusChangedEventHandler( Object sender,
    AutomationFocusChangedEventArgs e)

그리고 UI 자동화 클라이언트의 다양한 메서드와 속성을 제공하는 Automation 클래스의 정적 메서드 AddAutomationFocusChangedEventHandler를 이용하여 이벤트 핸들러를 등록합니다.

public static void AddAutomationFocusChangedEventHandler(
    AutomationFocusChangedEventHandler eventHandler)

포커스 핸들러에서는 현재 포커스를 소유한 UI 자동화 요소를 참조하여 정보를 출력할 것입니다. UI 자동화 기술에서는 UI 자동화 요소를 표현한 AutomationElement 클래스를 제공하고 있으며 정적 속성 FocusedElement로 현재 포커스를 소유한 UI 자동화 요소를 참조할 수 있습니다.

그리고 AutomationElement의 Current 속성으로 UI 자동화 요소의 현재 속성을 얻어올 수 있습니다. 여기에서는 요소의 이름을 출력하기로 합시다.

using System;
using System.Windows.Automation;

namespace 포커스트래커_콘솔
{
    class Program
    {
        static void Main(string[] args)
        {
            AutomationFocusChangedEventHandler afceh =
                new AutomationFocusChangedEventHandler(FocusChanged);
            Automation.AddAutomationFocusChangedEventHandler(afceh);
            Console.ReadLine();
        }
        static void FocusChanged(object sender, AutomationFocusChangedEventArgs e)
        {            
            AutomationElement ae = AutomationElement.FocusedElement;
            Console.WriteLine("Name:{0}", ae.Current.Name);
        }
    }
}

[소스 2.1] Program.cs