Windows UIA自动化测试框架学习(二)--获取qq好友列表

这个小功能还是通过win32API+UIA框架实现的,获取到qq好友列表中的成员备注名称,图中的好友姓名只取姓氏。

Windows UIA自动化测试框架学习(二)--获取qq好友列表

用到的API如下:

private const int MOUSEEVENTF_LEFTDOWN = 0x0002;//press the  mouse left button 
private const int MOUSEEVENTF_LEFTUP = 0x0004; //release the mouse right button
private const int MOUSEEVENTF_WHEEL = 0x800;//mouse wheel 
[DllImport("user32.dll", EntryPoint = "FindWindow")] 
private static extern IntPtr findWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll")]
private static extern int mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo);
[DllImport("user32.dll", EntryPoint = "SetCursorPos")]
private static extern bool setCursorPos(int X, int Y);

第一个API是为了获取qq窗口的句柄,第二个和第三个是用来模拟鼠标操作。

主程序代码很简单,写的有些粗糙。基本流程是先检索到列表名称的控件,然后通过获取坐标控制鼠标点击将列表展开,检索该列表中所有的成员。检索完成后将列表重新隐藏,避免列表成员太多,列表太长,影响下一个列表的展开。

IntPtr ptr = findWindow(null,"QQ");
            List<string> tables = new List<string>() {"高中","小学","初中","网友","大学"};//好友列表名称
            AutomationElement _mainElement = AutomationElement.FromHandle(ptr);
            foreach (var item in tables)
            {
                PropertyCondition type = new PropertyCondition(AutomationElement.IsControlElementProperty, true);
                PropertyCondition name = new PropertyCondition(AutomationElement.NameProperty, item);
                AutomationElement tableElement = _mainElement.FindFirst(TreeScope.Subtree, new AndCondition(type, name));
                if(tableElement!=null)
                {
                    Click(tableElement.GetClickablePoint().X, tableElement.GetClickablePoint().Y);//展开列表
                    AutomationElementCollection ac = _mainElement.FindAll(TreeScope.Subtree, new PropertyCondition(AutomationElement.IsSelectionItemPatternAvailableProperty, true));
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine(tableElement.Current.Name+":");
                    Console.ForegroundColor = ConsoleColor.White;
                    foreach (AutomationElement ele in ac)
                    {
                        Console.WriteLine(ele.Current.Name.Substring(0, 1) + "**");
                    }
                    Click(tableElement.GetClickablePoint().X, tableElement.GetClickablePoint().Y);//重新隐藏列表
                }

            }

            Console.ReadLine();

通过控制鼠标的API和UIA框架基本可以实现模拟任何人为操作,对实现windows app自动化测试是一个不错的选择