NEWS

[C#] Hướng dẫn Hook Event Text Changed, Set, Get Text Notepad sử dụng thư viện UI Automation Client API

[C#] Hướng dẫn Hook Event Text Changed, Set, Get Text Notepad sử dụng thư viện UI Automation Client API
Đăng bởi: Thảo Meo - Lượt xem: 9291 13:36:06, 11/10/2019C#   In bài viết

Xin chào các bạn, bài viết hôm nay mình sẽ hướng dẫn các bạn cách Hook Event, set và get Text ứng dụng Notepad sử dụng thư viện UI Automation Client C#.

[C#] Demo ứng dụng sử dụng UI Automation Client Hook Event Another Application

Thư viện UI Automation Client được Microsoft cung cấp trong .Net Framework, các bạn có thể import thư viện này vào project của mình.

Trong bài viết này, mình sẽ demo các set text, get text, và bắt sự kiện Textchanged từ một ứng dụng khác (hay đơn giản gọi cho dễ hiểu là điều khiển ứng dụng).

Bài này, mình sẽ demo với ứng dụng Notepad, các bạn có thể đọc bài viết này rồi làm việc với một ứng dụng Win32 bất kỳ nào khác.

Dưới đây là demo ứng dụng sử dụng Hook Event TextChanged Notepad:

hook_ui_automation_csharp_demo1]

 

Trong bài viết này, để lấy được ID của ứng dụng, các bạn có thể sử dụng phần mềm spy++ hoặc AutoIT hay Tool gì khác để lấy ID.

Trong source code bên dưới, mình khi gọi ứng dụng Notepad xong, mình có truyền vào trực tiếp id = 15, tương ứng với control nhập Text của Notepad.

Automation_Client

Full source code UI Automation Hook Event C#:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Automation;
using System.Windows.Forms;

namespace Hook_UI_Automation
{
    public partial class Frm_Main : Form
    {
        private AutomationElement mainWnd;
        private AutomationElement propertiesBtn;
        public Frm_Main()
        {
            InitializeComponent();
        }

        private void btn_start_Click(object sender, EventArgs e)
        {
            mainWnd = StartApp("notepad");
            if (mainWnd != null)
            {              
                Automation.AddAutomationEventHandler(WindowPattern.WindowClosedEvent, mainWnd, TreeScope.Element, OnTargetClose);             
                PropertyCondition btnIdCond = new PropertyCondition(AutomationElement.AutomationIdProperty, "15");
                propertiesBtn = mainWnd.FindFirst(TreeScope.Descendants, btnIdCond); 
            }
        }

        private void btn_CloseApp_Click(object sender, EventArgs e)
        {
            if (mainWnd != null)
            {
                ((WindowPattern)mainWnd.GetCurrentPattern(WindowPattern.Pattern)).Close();
            }
        }

        private AutomationElement StartApp(string app)
        {         
            Process p = Process.Start(app);          
            p.WaitForInputIdle(2000);         
            return (AutomationElement.FromHandle(p.MainWindowHandle));
        }
        private void OnTargetClose(object sender, AutomationEventArgs e)
        {
            mainWnd = null;           
        }

        private void btn_settext_Click(object sender, EventArgs e)
        {
            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("https://laptrinhvb.net!");
                }
                else
                {
                    nameTxt.SetFocus();
                    SendKeys.SendWait("^{HOME}");  
                    SendKeys.SendWait("^+{END}"); 
                    SendKeys.SendWait("{DEL}");   
                    SendKeys.SendWait(txt_input.Text);
                }
            }
        }

        private void btn_getText_Click(object sender, EventArgs e)
        {
            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;
                txt_output.Text = txtPattern.DocumentRange.GetText(-1);
            }
        }

        private void btn_Subscribe_Click(object sender, EventArgs e)
        {
            if (propertiesBtn != null)
            {
                Automation.AddAutomationEventHandler(InvokePattern.InvokedEvent, propertiesBtn, TreeScope.Descendants, OnTextChanged);
                lbl_status.Text = "Subscribed to event Text Changed!";
            }
            else
            {
                lbl_status.Text = "'Properties' Control not found";
            }
        }

        private void OnTextChanged(object sender, AutomationEventArgs e)
        {
            AutomationElement senderElement = sender as AutomationElement;
            if (e.EventId == InvokePattern.InvokedEvent)
            {
                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;
                    txt_textChanged.BeginInvoke(new Action(() => {

                        txt_textChanged.Text = txtPattern.DocumentRange.GetText(-1);

                    }));
                }

            }
           
        }

        private void btn_UNSubscribe_Click(object sender, EventArgs e)
        {
            Automation.RemoveAutomationEventHandler(InvokePattern.InvokedEvent, propertiesBtn, OnTextChanged);
            lbl_status.Text = "Unregistered Event!";
        }

        private void btn_save_Click(object sender, EventArgs e)
        {
            mainWnd.SetFocus();           
            Thread.Sleep(100);        
            SendKeys.Send("^S");
        }

        private void Frm_Main_FormClosing(object sender, FormClosingEventArgs e)
        {
            if(mainWnd != null)
            {
                ((WindowPattern)mainWnd.GetCurrentPattern(WindowPattern.Pattern)).Close();
            }
        }
    }
}

Thanks for watching!

Video Demo ứng dụng:

DOWNLOAD SOURCE

THÔNG TIN TÁC GIẢ

BÀI VIẾT LIÊN QUAN

[C#] Hướng dẫn Hook Event Text Changed, Set, Get Text Notepad sử dụng thư viện UI Automation Client API
Đăng bởi: Thảo Meo - Lượt xem: 9291 13:36:06, 11/10/2019C#   In bài viết

CÁC BÀI CÙNG CHỦ ĐỀ

Đọc tiếp
.