//启动被测试的程序
Process p = Process.Start("测试程序路径");
//自动化根元素
AutomationElement aeDeskTop = AutomationElement.RootElement;
//启动程序的时间
Thread.Sleep(3000);
//获取到程序的主界面
AutomationElement aeFrom = AutomationElement.FromHandle(p.MainWindowHandle);
//用于获取到程序的主界面计数
int numWaits = 0;
do
{
//查找第一个自动化元素
aeFrom = aeDeskTop.FindFirst(TreeScope.Children,
new PropertyCondition(AutomationElement.NameProperty, "MainWindow"));
} while (null == aeFrom && numWaits < 50);//限制
//主界面为空时抛出异常
if (null == aeFrom)
{
throw new NullReferenceException("启动测试失败");
}
AutomationElement aeComboBox = aeFrom.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.AutomationIdProperty, "cbbProductCode"));
ExpandCollapsePattern expandPattern = (ExpandCollapsePattern)aeComboBox.GetCurrentPattern(ExpandCollapsePattern.Pattern);
//重点来了,先要将ComBox展开后才能进行选择
expandPattern.Expand();
AutomationElementCollection rows = aeComboBox.FindAll(TreeScope.Subtree, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.ListItem));
AutomationElement comboboxItem = (AutomationElement)rows[i];
SelectionItemPattern selectPattern = (SelectionItemPattern)comboboxItem.GetCurrentPattern(SelectionItemPattern.Pattern);
selectPattern.Select();