前提工作:
①需要引入命名空间:using System.Windows.Automation;
②添加两个引用:UIAutomationClient、UIAutomationTypes
csusing 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; }