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 自动化框架与应用程序的用户界面进行交互。它通过搜索应用程序的界面层级结构来定位登录按钮,并模拟点击操作。
相关推荐
曹牧9 小时前
C#:输入的字符串格式不正确
c#
Canmag 兴隆磁性10 小时前
磁材包装产线自动化实践:自动定量装袋设备的原理、结构与选型思路
运维·自动化·永磁材料·包装
ZXCher11 小时前
危废库应急响应系统设计:越华环保集团泄漏/火灾场景下的自动化与硬件联动架构
大数据·架构·自动化
云飞云共享云桌面11 小时前
钣金精密机械工厂:多工程师共享图形服务器,SolidWorks/UG 三维设计兼顾成本与数据安全
运维·服务器·人工智能·自动化·制造
南讯股份Nascent11 小时前
私域SCRM系统架构拆解:从身份图谱到自动化触达引擎的选型要点
自动化·用户运营·零售
博图光电11 小时前
笔记本键盘漏光缺陷检测
人工智能·数码相机·3d·自动化
金八梭12 小时前
汽车工厂参观
自动化·电气工程
泵管家12 小时前
船舶压载水系统水泵控制解决方案分析与选型参考
经验分享·自动化
我是海飞12 小时前
杰理 JL703N SDK 实现 AI 自动化调试:自动进入下载模式、下载、重启与日志抓取
人工智能·单片机·自动化·音视频·杰理
兰亭妙微UI设计公司13 小时前
兰亭妙微用户体验设计公司的设计细节:关于提示的那些事
ui·ux·ue