c#使用UIA进行模拟点击操作

之前,我写过一篇c#使用spy进行模拟操作的文章,有朋友在留言中提到了UIA进行操作,今天也使用UIA重新实现一次对vnc窗体的控制测试。

实现目标

b2

在server框内填入192.168.2.200

自动点击Options按钮。

工具介绍

uispy,使用此工具查找窗体。可在我的csdn上下载,下载uispy

b1

在uispy内,找到我们需要操作的窗点,点击每行,将会使用红色边框线自动框选对应的窗口。

代码编写

a3

执行结果如上图。

//找到名称为 VNC Viewer : Connection Details 的窗体
            var desktop = AutomationElement.RootElement;//得到桌面
            //创建一个搜索条件,条件标明使用name属性,值为我们需要找的窗体名称。
            var condition = new PropertyCondition(AutomationElement.NameProperty, "VNC Viewer : Connection Details");
            //查找符合条件的第一个窗体.
            var window = desktop.FindFirst(TreeScope.Children, condition);

            //在需要的窗体上查找到options按钮并执行点击
            var btncondition = new AndCondition(
                    new PropertyCondition(AutomationElement.ControlTypeProperty,ControlType.Button),
                    new PropertyCondition(AutomationElement.NameProperty,"Options...")
                );
            //找按钮
            var buttonoption = window.FindFirst(TreeScope.Children, btncondition);
            //获取按钮可操作事件
            var clickPattern = (InvokePattern)buttonoption.GetCurrentPattern(InvokePattern.Pattern);
            //执行事件
            clickPattern.Invoke();

            //GOOD,上面的代码都很顺利的执行,接下来我们继续实现向文本框内输入结果
            //使用同样的方法先找到文本框
            var txtcondition = new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit);
            //Descendants 这里注意,因为现在文本框不是窗口的直接子级,因此不可以直接使用Children.
            var txtbox = window.FindFirst(TreeScope.Descendants, txtcondition);
            var editPatten = (ValuePattern)txtbox.GetCurrentPattern(ValuePattern.Pattern);
            editPatten.SetValue("192.168.2.200");

参考资料

http://www.cnblogs.com/coderzh/archive/2009/11/14/1603109.html

http://www.cnblogs.com/stbchina/archive/2010/01/28/Tech-Trend-of-Microsoft-UI-Automation-Testing-Part-Two.html

posted @ 2014-09-19 13:25  迟来的春天  阅读(2913)  评论(0编辑  收藏  举报