NGMsoftware

NGMsoftware
로그인 회원가입
  • 매뉴얼
  • 학습
  • 매뉴얼

    학습


    C# UIA 메모장에 텍스트 쓰기 및 읽기 예제 코드. (Microsoft UI Automation)

    페이지 정보

    본문

    안녕하세요. 엔지엠소프트웨어입니다. 윈도우에는 UI 자동화를 위한 Automation을 제공해주고 있습니다. 윈도우 소프트웨어를 테스트할 때 사용하는데요. 아래 예제 코드는 메모장에 텍스트를 쓰거나 가져오는 프로그램입니다. Visual Studio에서 콘솔 프로젝트를 하나 만들고, 실행 해보세요. 메모장은 미리 실행되어 있어야 합니다.

    using System;
    using System.Diagnostics;
    using System.Windows.Automation;
    using System.Windows.Forms;
    
    namespace ConsoleApp1
    {
        internal class Program
        {
            private static AutomationElement mainWnd;
    
            static void Main(string[] args)
            {
                Process[] procs = Process.GetProcessesByName("notepad");
    
                foreach (Process proc in procs) 
                {
                    mainWnd = AutomationElement.FromHandle(proc.MainWindowHandle);
    
                    Automation.AddAutomationEventHandler(WindowPattern.WindowClosedEvent, mainWnd, TreeScope.Element, OnTargetClose);
                    PropertyCondition btnIdCond = new PropertyCondition(AutomationElement.AutomationIdProperty, "15");
    
                    setText();
                    //getText();
                }
    
                Console.ReadKey();
            }
    
            private static void OnTargetClose(object sender, AutomationEventArgs e)
            {
                mainWnd = null;
            }
    
            private static void setText()
            {
                PropertyCondition idCond = new PropertyCondition(AutomationElement.AutomationIdProperty, "15");
                AutomationElement nameTxt = mainWnd.FindFirst(TreeScope.Descendants, idCond);
                if (nameTxt != null)
                {
                    nameTxt.SetFocus();
    
                    if (nameTxt.TryGetCurrentPattern(ValuePattern.Pattern, out object pattern))
                    {
                        ((ValuePattern)pattern).SetValue("http://ngmsoftware.com");
                    }
                    else
                    {
                        nameTxt.SetFocus();
                        SendKeys.SendWait("^{HOME}");
                        SendKeys.SendWait("^+{END}");
                        SendKeys.SendWait("{DEL}");
                        SendKeys.SendWait("http://ngmsoftware.com");
                    }
                }
            }
    
            private static void getText()
            {
                PropertyCondition idCond = new PropertyCondition(AutomationElement.AutomationIdProperty, "15");
                AutomationElement nameTxt = mainWnd.FindFirst(TreeScope.Descendants, idCond);
                if (nameTxt != null)
                {
                    TextPattern txtPattern = nameTxt.GetCurrentPattern(TextPattern.Pattern) as TextPattern;
                    Console.Write(txtPattern.DocumentRange.GetText(-1));
                }
            }
        }
    }

     

    크게 복잡한 내용은 없어서 이해하는데 어려움은 없을거예요. 참고로, UI Automation에서 AutomationElement로 컨트롤을 바인딩하고, 조작하는 방식을 사용합니다. 콘트롤 타입이 ValueType인 경우에만 SetValue 메소드를 사용할 수 있습니다. 하지만, 메모장도 텍스트 입력기인데 콘트롤 타입은 Edit입니다. Edit에는 Write나 SetValue와 같은 메소드가 없어서 텍스트 쓰기는 우회해야 합니다. 그래서, 윈도우 오토메이션을 이용해서 RPA나 매크로를 만들기는 쉽지 않습니다. 대부분 API를 따거나 win32 API를 사용해서 부족한 부분들을 처리해야 합니다.

     

    개발자에게 후원하기

    MGtdv7r.png

     

    추천, 구독, 홍보 꼭~ 부탁드립니다.

    여러분의 후원이 빠른 귀농을 가능하게 해줍니다~ 답답한 도시를 벗어나 귀농하고 싶은 개발자~

    감사합니다~

    • 네이버 공유하기
    • 페이스북 공유하기
    • 트위터 공유하기
    • 카카오스토리 공유하기
    추천0 비추천0

    댓글목록

    등록된 댓글이 없습니다.