使用UI自动化更改WinForms组合框选择

Noi*_*ves 5 c# user-interface automation .net-3.5

是否可以使用c#UI自动化(与UIspy.exe相同的逻辑)更改winforms应用程序中的选定项目?我想将所选项目更改为特定项目(我知道它在列表中的索引/位置).

小智 2

    public static void ActionSelectComboBoxItem(AutomationElement comboBoxElement, int indexToSelect){
        if(comboBoxElement == null)
            throw new Exception("Combo Box not found");

        //Get the all the list items in the ComboBox
        AutomationElementCollection comboboxItem = comboBoxElement.FindAll(TreeScope.Children, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.ListItem));

        //Expand the combobox
        ExpandCollapsePattern expandPattern = (ExpandCollapsePattern)comboBoxElement.GetCurrentPattern(ExpandCollapsePattern.Pattern);
        expandPattern.Expand();

        //Index to set in combo box
        AutomationElement itemToSelect = comboboxItem[indexToSelect];

        //Finding the pattern which need to select
        SelectionItemPattern selectPattern = (SelectionItemPattern)itemToSelect.GetCurrentPattern(SelectionItemPattern.Pattern);
        selectPattern.Select();
    }
Run Code Online (Sandbox Code Playgroud)