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 自动化框架与应用程序的用户界面进行交互。它通过搜索应用程序的界面层级结构来定位登录按钮,并模拟点击操作。
相关推荐
时光追逐者4 小时前
C#/.NET/.NET Core技术前沿周刊 | 第 46 期(2025年7.7-7.13)
c#·.net·.netcore
mit6.8245 小时前
Why C# and .NET are still relevant in 2025
c#
liulilittle5 小时前
.NET ExpandoObject 技术原理解析
开发语言·网络·windows·c#·.net·net·动态编程
七夜zippoe5 小时前
破解 VMware 迁移难题:跨平台迁移常见问题及自动化解决方案
运维·自动化·vmware
军训猫猫头6 小时前
5.浏览本地文件获取路径与文件名称 C#例子 WPF例子
开发语言·c#·wpf
IT信息技术学习圈6 小时前
AI交互中的礼貌用语:“谢谢“的效用与代价分析
人工智能·交互
王柏龙10 小时前
aspnetcore Mvc配置选项中的ModelBindingMessageProvider
mvc·.net
Listennnn11 小时前
Agent自动化与代码智能
人工智能·自动化
SEO-狼术12 小时前
DevExtreme Complete Crack,responsive UI widgets
ui
步、步、为营14 小时前
.NET + WPF框架开发聊天、网盘、信息发布、视频播放功能
.net·wpf·音视频