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 自动化框架与应用程序的用户界面进行交互。它通过搜索应用程序的界面层级结构来定位登录按钮,并模拟点击操作。
相关推荐
江边风声19 分钟前
PCB自动化收放板机 在薄板制程中的特殊取放策略——0.05mm芯板怎么稳抓不掉
人工智能·科技·自动化·制造·pcb工艺
lzhdim27 分钟前
C# 中读取CPU、硬盘和内存温度
开发语言·c#
驰骋工作流1 小时前
请假流程:六款.NET工作流引擎实现方式对比
.net·ccflow·工作流引擎二开·.net工作流引擎对比
AI行业说1 小时前
美国布艺市场全品类生产解析——誉财YC-18-M8045四轴模板机的多品种柔性制造方案
大数据·人工智能·自动化·智能家居·自动化缝纫
WarPigs1 小时前
.NET项目app.Config笔记
c#·.net
薛定谔的猫-菜鸟程序员2 小时前
一个 Skill 如何让大模型拥有专业 UI 能力?——ui-ux-pro-max 架构深度拆解与 Skill 设计方法论
人工智能·ui
液态不合群2 小时前
AI+低代码破局:零售全域数据壁垒的落地新范式
人工智能·低代码·自动化·零售
隔窗听雨眠2 小时前
GitHub Actions自动化运维实战:从零构建一体化CI/CD流水线
运维·自动化·github
MXsoft6184 小时前
在大型混合云网络环境中,如何高效实现自动化运维?
运维·网络·自动化