【环境】
操作系统:Windows7
集成环境:Visual Studio2015
编程语言:C#
目标框架:.net framework4.6
1、新建项目
Visual Studio 2015 【文件】->【新建】->【项目】->Visual C#(控制台应用程序)
2、添加引用
项目->引用->添加引用-> 打开引用管理器,在程序集搜索UIAutomation
引用 UIAutomationClient、UIAutomationClientsideProviders、UIAutomationProvider、UIAutomationTypes。
备注:这4个dll文件所在路径:C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0
3、Inspect.exe和UISpy.exe工具
查找控件属性
4、demo脚本
该demo脚本可启动应用程序并进行登录
using System.Diagnostics;
using System.Threading;
using System.Windows.Automation;
namespace myProject01
{
class Program
{
static void Main(string[] args)
{
Process p = Process.Start(@"D:\xx\xx.exe");//启动应用程序
Thread.Sleep(10000);
AutomationElement desktop = AutomationElement.RootElement;//获取RootElement
//获取当前窗口
AutomationElement posframe = desktop.FindFirst(TreeScope.Descendants | TreeScope.Children,
new PropertyCondition(AutomationElement.AutomationIdProperty, "SystemLogin"));
//输入用户名控件
AutomationElement usertext = posframe.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.AutomationIdProperty, "txt_no"));
//输入密码控件
AutomationElement pwdtext = posframe.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.AutomationIdProperty, "pb_pwd"));
//登录控件
AutomationElement loginBtn = posframe.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.AutomationIdProperty, "btn_login"));
//输入用户名
ValuePattern username = (ValuePattern)usertext.GetCurrentPattern(ValuePattern.Pattern);
username.SetValue("0114");
//输入密码
ValuePattern password = (ValuePattern)pwdtext.GetCurrentPattern(ValuePattern.Pattern);
password.SetValue("0114");
//点击登录
InvokePattern ivkp = (InvokePattern)loginBtn.GetCurrentPattern(InvokePattern.Pattern);
ivkp.Invoke(); //触发控件事件
}
}
}
知识兔