views:

151

answers:

1

We are using the code below to get a list of items out of a ComboBox inside another application's window. This code works (correctly retrieves the list of items) for ComboBoxes in any other application we've tested this code on, however for this particular application the Name property retrieved for each ListItem is garbled.

Here is the code:

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);
}

And here is a screenshot of what we end up with for this one app.

alt text

  • What could cause the Name property to be garbled like this? Could this be an encoding problem?
  • How can we get the correct text for each item?
+1  A: 

If this combobox has the CBS_OWNERDRAWFIXED or CBS_OWNERDRAWVARIABLE style, or the contained listbox has the LBS_OWNERDRAWFIXED or LBS_OWNERDRAWVARIABLE style. then the text isn't known by the control at all. When an app uses one of these styles, it gets WM_DRAWITEM messages whenever the control needs to draw, then it pulls the text from it's pocket and draws it wherever it was asked to.

This is a trick that allows an application to quickly and easily change the contents of a listbox or combobox on the fly, it's mostly used when the contents are volatile or when there are LOTS of items. It's one way to get around the limit on the number of items an listbox/combobox can hold.

Use Spy++ to check the styles on these windows.

John Knoeller
I checked it out with SPY++ and this does appear to be the issue. Thank you for the clear explanation!
Joshua Poehls