C# 利用 UI 自动化框架与应用程序的用户界面进行交互来模拟点击按钮

前提工作:

①需要引入命名空间:using System.Windows.Automation;

②添加两个引用:UIAutomationClient、UIAutomationTypes

cs 复制代码
using System.Windows.Automation;  
private static void AutoClickLoginButton()
        {
            //进程名称 可替换为你程序的进程
            string appName = "FR";
            Process[] myProcesses = Process.GetProcessesByName(appName);

            if (myProcesses.Length > 0) // 如果程序已经启动
            {
                Process targetProcess = myProcesses[0];
                AutomationElement rootElement = AutomationElement.FromHandle(targetProcess.MainWindowHandle);

                AutomationElement loginButton = FindLoginButton(rootElement);

                if (loginButton != null)
                {
                    // 使用 InvokePattern 模拟点击登录按钮
                    InvokePattern invokePattern = loginButton.GetCurrentPattern(InvokePattern.Pattern) as InvokePattern;
                    invokePattern.Invoke();
                }
            }
        }

        private static AutomationElement FindLoginButton(AutomationElement element)
        {
            // 查找子元素 查找子窗体下的按钮的名称 根据实际情况修改
            AutomationElement loginButton = element.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.NameProperty, "登录"));
            if (loginButton != null)
            {
                return loginButton;
            }
            // 递归查找子元素
            AutomationElementCollection children = element.FindAll(TreeScope.Children, Condition.TrueCondition);
            foreach (AutomationElement child in children)
            {
                loginButton = FindLoginButton(child);
                if (loginButton != null)
                {
                    return loginButton;
                }
            }
            return null;
        }

实现原理:

当程序已经启动时,AutoClickLoginButton 方法会寻找名为"FR"的应用程序进程。然后,它使用 AutomationElement.FromHandle 从该进程的主窗口句柄获取根元素。
接着,FindLoginButton 方法被调用,该方法在根元素及其子元素中递归查找名为"登录"的登录按钮。
如果找到登录按钮,代码会使用 InvokePattern 模拟点击登录按钮。InvokePattern.Invoke() 方法会模拟用户点击按钮的动作。
整体来说,这段代码利用 UI 自动化框架与应用程序的用户界面进行交互。它通过搜索应用程序的界面层级结构来定位登录按钮,并模拟点击操作。
相关推荐
黄毛火烧雪下5 小时前
【Ruby 】脚本和自动化语言 常用的内容
运维·自动化·ruby
加号39 小时前
【C#】获取电脑网卡MAC地址
windows·c#
yi碗汤园9 小时前
【超详细】C#自定义工具类-StringHelper
开发语言·前端·unity·c#·游戏引擎
sali-tec9 小时前
C# 基于halcon的视觉工作流-章49-网面破损
开发语言·图像处理·算法·计算机视觉·c#
YuanlongWang9 小时前
c# ABP vNext 框架详解及其模块化开发思想介绍
开发语言·c#
发光小北9 小时前
4路can转4g功能介绍
自动化
张人玉9 小时前
WPF布局控件(界面骨架核心)
开发语言·c#·wpf·布局控件
广商 小轩12 小时前
自动化实战 Playwright破解滑块验证码的完整实战指南
运维·自动化
刘欣的博客12 小时前
C# 上传票据文件 调用Dify的API完成OCR识别
c#·ocr·api·dify
hoiii18712 小时前
C#实现近7天天气预报
开发语言·c#