Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (seongtaejeong at gmail.com)
홈페이지
첨부 파일

(시리즈 글이 2개 있습니다.)
.NET Framework: 496. 마우스 커서가 놓인 지점의 문자열 얻는 방법
; https://www.sysnet.pe.kr/2/0/1861

닷넷: 2366. C# - UIAutomationClient를 이용해 시스템 트레이의 아이콘을 열거하는 방법
; https://www.sysnet.pe.kr/2/0/14018




C# - UIAutomationClient를 이용해 시스템 트레이의 아이콘을 열거하는 방법

UIAutomationClient.dll의 경우 .NET Framework과 함께 배포되므로 아래의 경로에서 찾을 수 있습니다.

C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.0\UIAutomationClient.dll
C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.0\UIAutomationTypes.dll

(내부 의존성에 의해 "UIAutomationProvider.dll"도 자동 참조됨)

따라서 Visual Studio의 경우 참조 추가 메뉴를 사용하거나, 혹은 직접 csproj에 추가해도 됩니다.

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />

  <!-- ...[생략]... -->

  <ItemGroup>
    <!-- ...[생략]... -->
    <Reference Include="UIAutomationClient">
      <HintPath>C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.0\UIAutomationClient.dll</HintPath>
    </Reference>
    <Reference Include="UIAutomationTypes">
      <HintPath>C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.0\UIAutomationTypes.dll</HintPath>
    </Reference>
  </ItemGroup>

  <!-- ...[생략]... -->

</Project>

적절한 예제 코드를 다음의 글에서 찾을 수 있는데요,

Enumerating notification icons via UI Automation
; https://devblogs.microsoft.com/oldnewthing/20141013-00/?p=43863

따라서 이렇게 코딩을 추가하고,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Automation;

internal class Program
{
    static void Main(string[] args)
    {
        foreach (var icon in EnumNotificationIcons())
        {
            string name = icon.GetCurrentPropertyValue(AutomationElement.NameProperty) as string;
            if (name == null)
            {
                continue;
            }
        }
    }

    public static IEnumerable<AutomationElement> EnumNotificationIcons()
    {
        Console.WriteLine("[Enumerating User Promoted Notification Area...]");
        var userArea = AutomationElement.RootElement.Find(
                          "User Promoted Notification Area");
        if (userArea != null)
        {
            foreach (var button in userArea.EnumChildButtons())
            {
                Console.WriteLine($"\t{RemoveLine(button.Current.Name)}");
                yield return button;
            }

            Console.WriteLine("\n\t[Enumerating System Promoted Notification Area...]");
            foreach (var button in userArea.GetTopLevelElement().Find(
                          "System Promoted Notification Area").EnumChildButtons())
            {
                Console.WriteLine($"\t\t{RemoveLine(button.Current.Name)}");
                yield return button;
            }
        }

        Console.WriteLine("\n[Enumerating Notification Chevron...]");
        var chevron = AutomationElement.RootElement.Find("Notification Chevron");
        if (chevron != null && chevron.InvokeButton())
        {
            Console.WriteLine("\n\t[Enumerating Overflow Notification Area...]");
            foreach (var button in AutomationElement.RootElement.Find(
                               "Overflow Notification Area").EnumChildButtons())
            {
                Console.WriteLine($"\t\t{RemoveLine(button.Current.Name)}");
                yield return button;
            }
        }
    }

    static string RemoveLine(string s)
    {
        return s.Replace("\n", ", ").Replace("\r", "");
    }
}

static class AutomationElementHelpers
{
    public static AutomationElement Find(this AutomationElement root, string name)
    {
        return root.FindFirst(
         TreeScope.Descendants,
         new PropertyCondition(AutomationElement.NameProperty, name));
    }

    public static IEnumerable<AutomationElement> EnumChildButtons(this AutomationElement parent)
    {
        return parent == null ? Enumerable.Empty<AutomationElement>()
                              : parent.FindAll(TreeScope.Children,
          new PropertyCondition(AutomationElement.ControlTypeProperty,
                                ControlType.Button)).Cast<AutomationElement>();
    }

    public static bool InvokeButton(this AutomationElement button)
    {
        var invokePattern = button.GetCurrentPattern(InvokePattern.Pattern)
                           as InvokePattern;
        if (invokePattern != null)
        {
            invokePattern.Invoke();
        }
        return invokePattern != null;
    }

    static public AutomationElement GetTopLevelElement(this AutomationElement element)
    {
        AutomationElement parent;
        while ((parent = TreeWalker.ControlViewWalker.GetParent(element)) !=
             AutomationElement.RootElement)
        {
            element = parent;
        }
        return element;
    }
}

다음과 같은 tray 상황에서,

ui_auto_reference_3.png

실행하면 이런 결과가 나옵니다.

c:\temp> ConsoleApp2.exe
[Enumerating User Promoted Notification Area...]
        testad.com, Internet access
        The Audio Service is not running.

        [Enumerating System Promoted Notification Area...]

[Enumerating Notification Chevron...]

        [Enumerating Overflow Notification Area...]
                CPU 12%Memory 24%

위의 결과에서 재미있는 부분은, (CPU 12%Memory 24% 툴팁 텍스트를 보여주는) "작업 관리자" 아이콘의 경우 "펼침" 버튼이 (사용자가 아닌) 코드에 의해 눌려 나타나게 되었다는 점입니다. 왜냐하면 UI Automation은 실제로 UI 요소가 있어야만 찾을 수 있기 때문에, 아래의 코드가 그 동작을 수행해,

Console.WriteLine("\n[Enumerating Notification Chevron...]");
var chevron = AutomationElement.RootElement.Find("Notification Chevron");
if (chevron != null && chevron.InvokeButton())
{
    // ...[생략]...
}

숨겨진 아이콘을 펼치고 나서 "작업 관리자" 아이콘을 찾을 수 있었던 것입니다.




참고로, 하드 코딩된 UI 요소의 이름은 각각 다음과 같습니다.

User Promoted Notification Area
System Promoted Notification Area

SPY++로 찾아보면 "TrayNotifyWnd"라는 윈도우 클래스를 가진 하위에서 찾을 수 있는 윈도우인데,

ui_auto_reference_2.png

유의해야 할 점은, 이 문자열이 다국어 처리가 돼 있기 때문에, 가령 한글 윈도우라면 각각 다음과 같이 바뀝니다. (의미인즉, 범용으로 저 코드를 사용하기는 힘들다는 뜻입니다.)

사용자 지정 알림 영역
시스템 프롬프트 알림 영역

그리고 또 한 가지 더 유의할 점이 있는데요, 작업 관리자의 구조 변화로 인해 Windows 11 / Windows Server 2025부터는 "TrayNotifyWnd"가 하위 윈도우를 갖지도 않고 저 이름에 해당하는 UI 요소도 없어졌으므로 출력이 나오지 않습니다. (세밀하게 테스트한 것은 아니지만, 대략 10.0.26100 버전부터 바뀐 것 같습니다.)




재미 삼아 위의 작업을 .NET Core/5+ 프로젝트로도 시도해 봤습니다. 그런데, Visual Studio에서 .NET Core/5+ 프로젝트의 경우 직접적인 DLL 참조를 위한 메뉴가 없군요. ^^

ui_auto_reference_0.png

보는 바와 같이 "Add Project Reference...", "Add Shared Project Reference...", "Add COM Reference..." 메뉴만 있고, DLL을 직접 참조할 수 있는 "Add Reference..." 메뉴가 없는데요, 상관없습니다. 그냥 아무거나 "Add ... " 메뉴를 선택해 일단 "Reference Manager" 창만 띄우면 이후 "Browse" 탭을 선택해 "Browse..." 버튼을 눌러 DLL 참조를 할 수 있습니다.

ui_auto_reference_1.png

혹은 그냥 csproj에 이렇게 추가해도 됩니다.

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

  <ItemGroup>
    <Reference Include="UIAutomationClient">
      <HintPath>C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.0\UIAutomationClient.dll</HintPath>
    </Reference>
    <Reference Include="UIAutomationTypes">
      <HintPath>C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.0\UIAutomationTypes.dll</HintPath>
    </Reference>
  </ItemGroup>

</Project>

하지만, 이 정도의 구성으로는 빌드 시 컴파일 오류는 없지만 실행 시 다음과 같은 예외가 발생합니다.

Unhandled exception. System.MissingMethodException: Method not found: 'System.Windows.Rect System.Windows.Automation.Provider.IRawElementProviderFragment.get_BoundingRectangle()'.
   at MS.Internal.Automation.UiaCoreApi.OnGetProvider(IntPtr hwnd, ProviderType providerType)
   at MS.Internal.Automation.UiaCoreApi.RawUiaGetRootNode(SafeNodeHandle& hnode)
   at MS.Internal.Automation.UiaCoreApi.UiaGetRootNode()
   at System.Windows.Automation.AutomationElement.get_RootElement()
   at ConsoleApp1.Program.EnumNotificationIcons()+MoveNext()
   at ConsoleApp1.Program.Main(String[] args)

검색해 보면 유사한 질문이 나오는데요,

C# Having issues with UIAutomation Reference- get_BoundingRectangle() method not found
; https://stackoverflow.com/questions/61987982/c-sharp-having-issues-with-uiautomation-reference-get-boundingrectangle-metho

아쉽게도 답은, .NET Framework 프로젝트로 해결했다고만 합니다. 실제 원인은 "Microsoft.NET.Sdk"가 UIAutomation 의존성을 갖지 않아 관련 어셈블리들이 로드되지 않기 때문으로 보입니다. 따라서 Console 프로젝트라면 다음과 같이 명시적으로 UseWindowsForms 옵션을 켜야만 합니다.

<Project Sdk="Microsoft.NET.Sdk">

    <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>net8.0-windows</TargetFramework>
        <UseWindowsForms>true</UseWindowsForms>
        <ImplicitUsings>enable</ImplicitUsings>
        <Nullable>enable</Nullable>
    </PropertyGroup>

    <!-- ...[생략]... -->

</Project>

혹은, 아래와 같은 글이 있는 걸로 봐서는,

How to use AutomationElement in a .NET Core 8 console application?
; https://www.simonmourier.com/blog/How-to-use-AutomationElement-in-a-NET-Core-8-console-application/

아예 COM 개체로 다뤄도 될 듯합니다. 단지 COM 개체보다는 .NET Assembly로 참조하는 것이 더 편리하므로 직접 DLL을 참조하는 것이 더 나을 것입니다.

(첨부 파일은 이 글의 예제 코드를 포함합니다.)


[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 10/2/2025]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
14019정성태10/1/2025549Linux: 124. eBPF - __sk_buff / sk_buff 구조체
14018정성태9/30/2025154닷넷: 2366. C# - UIAutomationClient를 이용해 시스템 트레이의 아이콘을 열거하는 방법파일 다운로드1
14017정성태9/29/2025591Linux: 123. eBPF (bpf2go) - BPF_PROG_TYPE_SOCKET_FILTER 예제 - SEC("socket")
14016정성태9/28/2025607Linux: 122. eBPF (bpf2go) - __attribute__((preserve_access_index)) 사용법
14015정성태9/22/20251224닷넷: 2365. C# - FFMpegCore를 이용한 MP4 동영상으로부터 MP3 음원 추출 예제파일 다운로드1
14014정성태9/17/20251307닷넷: 2364. C# - stun.l.google.com을 사용해 공용 IP 주소와 포트를 알아내는 방법파일 다운로드1
14013정성태9/14/20251985닷넷: 2363. C# - Whisper.NET Library를 이용해 음성을 텍스트로 변환 및 번역하는 예제파일 다운로드1
14012정성태9/9/20252095닷넷: 2362. C# - Windows.Media.Ocr: 윈도우 운영체제에 포함된 OCR(Optical Character Recognition)파일 다운로드1
14011정성태9/7/20252443닷넷: 2361. C# - Linux 환경의 readlink 호출
14010정성태9/1/20252290오류 유형: 983. apt update 시 "The repository 'http://deb.debian.org/debian buster Release' does not have a Release file." 오류
14009정성태8/28/20253108닷넷: 2360. C# 14 - (11) Expression Tree에 선택적 인수와 명명된 인수 허용파일 다운로드1
14008정성태8/26/20253474닷넷: 2359. C# 14 - (10) 복합 대입 연산자의 오버로드 지원파일 다운로드1
14007정성태8/25/20253793닷넷: 2358. C# - 현재 빌드에 적용 중인 컴파일러 버전 확인 방법 (#error version)
14006정성태8/23/20253986Linux: 121. Linux - snap 패키지 관리자로 설치한 소프트웨어의 디렉터리 접근 제한
14005정성태8/21/20253242오류 유형: 982. sudo: unable to load /usr/libexec/sudo/sudoers.so: libssl.so.3: cannot open shared object file: No such file or directory
14004정성태8/21/20253767오류 유형: 981. dotnet 실행 시 No usable version of the libssl was found
14003정성태8/21/20253855닷넷: 2357. C# 14 - (9) 새로운 지시자 추가 (Ignored directives)
14002정성태8/20/20254175오류 유형: 980. C# - appsettings.json 파일의 설정값이 적용 안 된다면?
14001정성태8/19/20258947닷넷: 2356. .NET SDK 10 - 단일 소스 코드 파일을 빌드/실행하는 기능을 "dotnet" 명령어에 추가 [1]
14000정성태8/18/20254332오류 유형: 979. ERROR: failed to solve: failed to read dockerfile: open Dockerfile: no such file or directory
13999정성태8/15/20254016닷넷: 2355. C# 14 - (8) null 조건부 연산자 개선 - 대입문에도 사용 가능파일 다운로드1
13998정성태8/14/20253631닷넷: 2354. C# 14 - (7) 확장 메서드에 정적 메서드와 속성 지원을 위한 전용 구문 추가파일 다운로드1
13997정성태8/14/20254290Linux: 120. docker 컨테이너로 매핑된 볼륨에 컨테이너 측의 사용자 ID를 유지하면서 복사하는 방법
13996정성태8/13/20253209오류 유형: 978. Unable to find the requested .Net Framework Data Provider.
13995정성태8/13/20253482개발 환경 구성: 754. Visual C++ - 리눅스 빌드를 위한 Ubuntu 18 docker 컨테이너 설정
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...