Search code examples
c#.netcomboboxui-automationmicrosoft-ui-automation

Windows UI Automation select item of combobox


I'm trying to select an item based on its value with the Windows UI Automation API.

I have a class ComboBox which inherits from UIAutomation.Element.

Further I have a method on this combobox element which should be able to be called with a string to select the matching combobox-item

I've tried the following:

public void SetSelectedItem(string itemName, ITimeout timeout = null)
{
    var comboboxItem = this.GetSelf(timeout).FindAll(TreeScope.Children, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.ListItem));

    var expandCollapsePattern = (ExpandCollapsePattern)this.GetSelf(timeout).GetCurrentPattern(ExpandCollapsePattern.Pattern);
    expandCollapsePattern.Expand();
    var itemToSelect = ?????

    var selectItemPattern = (SelectionItemPattern)itemToSelect.GetCurrentPattern(SelectionItemPattern.Pattern);
    selectItemPattern.Select();
}

But I don't really know how to retrieve the correct item at the line var itemToSelect = ?????.

The variable comboboxItem is of type AutomationElementCollection but unfortunately, Linq doesn't seem to be able with this type...

Do you know how to retrieve the correct item?

Or am I doing something else wrong?

Thanks in advance


Solution

  • I've found the answer thanks to the hints of @TnTinMn, thank you! :-)

    public void SetSelectedItem(string itemName, ITimeout timeout = null)
    {
        this.GetSelf(timeout).Expand();
    
        var list = this.GetSelf(timeout).FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.List), timeout);
        var listItem = list.FindFirst(TreeScope.Children, new PropertyCondition(AutomationElement.NameProperty, itemName), timeout);
    
        listItem.Select();
    }