使用UI Automation获取ComboBox中的项目时的结果很糟糕

时间:2009-12-18 16:34:52

标签: c# winapi ui-automation

我们使用下面的代码从另一个应用程序窗口中的ComboBox中获取项目列表。此代码在我们测试此代码的任何其他应用程序中工作(正确检索项目列表),但是对于此特定应用程序,为每个ListItem检索的Name属性都是乱码。

以下是代码:

using System.Windows.Automation;

var condition = new PropertyCondition(AutomationElement.NameProperty, "Change/Add/Delete Setting");
var condition2 = new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Window);
var condition3 = new AndCondition(new Condition[] {condition, condition2});
var window = AutomationElement.RootElement.FindFirst(TreeScope.Subtree, condition3);

condition = new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.ComboBox);
var combo = window.FindFirst(TreeScope.Subtree, condition);

condition = new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.ListItem);
AutomationElementCollection children = combo.FindAll(TreeScope.Subtree, condition);

var comboItems = new List<string>();
foreach (AutomationElement child in children)
{
    comboItems.Add(child.Current.Name);
}

这是我们为这个应用程序最终得到的截图。

alt text

  • 什么可能导致Name属性像这样乱码?这可能是编码问题吗?
  • 我们如何为每个项目获取正确的文字?

1 个答案:

答案 0 :(得分:3)

如果此组合框具有CBS_OWNERDRAWFIXEDCBS_OWNERDRAWVARIABLE样式,或者包含的列表框具有LBS_OWNERDRAWFIXEDLBS_OWNERDRAWVARIABLE样式。那么控制根本不知道文本。当应用程序使用其中一种样式时,只要控件需要绘制,它就会获取WM_DRAWITEM消息,然后从它的口袋中提取文本并将其绘制到需要的位置。

这是一个技巧,允许应用程序快速,轻松地动态更改列表框或组合框的内容,它主要用于内容易失或有 LOTS 项目时。这是绕过列表框/组合框可以容纳的项目数量限制的一种方法。

使用Spy ++检查这些窗口的样式。