Search code examples
windowswinapiwin32guimicrosoft-ui-automation

Checkbox (checked or unchecked)


While using automation client I am iterating over all the elements of the window.

And I want to get button...

[![enter image description here][1]][1]

Here is code...


How can I get any of these 3 property values without running through another UI.


Solution

  • Here is some sample code which, if Discord is ran, will print the "Mute" button state:

    #include <windows.h>
    #include <atlbase.h>
    #include <atlcom.h>
    #include <UIAutomationCore.h>
    #include <UIAutomationClient.h>
    
    int main()
    {
        // warning: error checks omitted!
        CoInitializeEx(NULL, COINITBASE_MULTITHREADED);
        {
            // start UIA & get root
            CComPtr<IUIAutomation> automation;
            automation.CoCreateInstance(CLSID_CUIAutomation8);
    
            CComPtr<IUIAutomationElement> root;
            automation->GetRootElement(&root);
    
            // find the "Discord" window
            CComPtr<IUIAutomationCondition> discordCondition;
            automation->CreatePropertyCondition(UIA_NamePropertyId, CComVariant(L"Discord"), &discordCondition);
    
            CComPtr<IUIAutomationElement> discord;
            root->FindFirst(TreeScope_Children, discordCondition, &discord);
    
            // create a name="Mute" && type = button condition
            CComPtr<IUIAutomationCondition> muteCondition;
            automation->CreatePropertyCondition(UIA_NamePropertyId, CComVariant(L"Mute"), &muteCondition);
    
            CComPtr<IUIAutomationCondition> buttonCondition;
            automation->CreatePropertyCondition(UIA_ControlTypePropertyId, CComVariant(UIA_ButtonControlTypeId), &buttonCondition);
    
            CComPtr<IUIAutomationCondition> andCondition;
            automation->CreateAndCondition(muteCondition, buttonCondition, &andCondition);
    
            // get "Mute" button
            CComPtr<IUIAutomationElement> muteButton;
            discord->FindFirst(TreeScope_Subtree, andCondition, &muteButton);
    
            // get toggle pattern
            CComPtr<IUIAutomationTogglePattern> toggle;
            muteButton->GetCurrentPatternAs(UIA_TogglePatternId, IID_PPV_ARGS(&toggle));
    
            // get toggle state
            ToggleState state;
            toggle->get_CurrentToggleState(&state);
    
            switch (state)
            {
            case ToggleState_Off:
                wprintf(L"state is off.\n");
                break;
    
            case ToggleState_On:
                wprintf(L"state is on.\n");
                break;
    
            case ToggleState_Indeterminate:
                wprintf(L"state is indeterminate.\n");
                break;
            }
        }
        CoUninitialize();
    }