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 自动化框架与应用程序的用户界面进行交互。它通过搜索应用程序的界面层级结构来定位登录按钮,并模拟点击操作。
相关推荐
LateFrames16 小时前
做【秒开】的程序:WPF / WinForm / WinUI3 / Electron
electron·c#·wpf·winform·winui3·claude code
Lynnxiaowen17 小时前
今天我们开始学习Linux自动化运维Ansible基础
linux·运维·学习·自动化·云计算·ansible
机器人行业研究员17 小时前
防爆六维力传感器的本质安全,破解高危环境自动化难题
运维·自动化
想拿大厂offer17 小时前
Windows Server 2022 + IIS + .NET 8 + MySQL 部署手册
c#·asp.net
小码编匠20 小时前
.NET 10 性能突破:持续优化才是质变关键
后端·c#·.net
软泡芙21 小时前
【.NET10】正式发布!微软开启智能开发生态新纪元
人工智能·microsoft·.net
q***25121 小时前
开源模型应用落地-FastAPI-助力模型交互-进阶篇-中间件(四)
开源·交互·fastapi
mudtools1 天前
.NET驾驭Excel之力:Excel应用程序的创建与管理
c#·.net·excel·wps
mudtools1 天前
.NET驾驭Excel之力:自动化数据处理 - 开篇概述与环境准备
c#·自动化·.net·excel·wps
拾光Ծ1 天前
Linux高效编程与实战:自动化构建工具“make/Makefile”和第一个系统程序——进度条
linux·运维·自动化·gcc