win32-UI Automation

使用UI Automation遍历窗口的所有控件标题和类

#include <Windows.h>
#include <stdio.h>
#include <UIAutomation.h>

IUIAutomation* pClientUIA;
IUIAutomationElement* pRootElement;

void FindControl(const long controlType)
{
    HRESULT hr;
    BSTR name;
    IUIAutomationCondition* pCondition;
    VARIANT varProp;
    varProp.vt = VT_I4;
    varProp.uintVal = controlType;
    hr = pClientUIA->CreatePropertyCondition(UIA_ControlTypePropertyId, varProp, &pCondition);
    if (S_OK != hr)
    {
        printf("CreatePropertyCondition error: %d\n", GetLastError());
    }

    IUIAutomationElementArray* pElementFound;
    hr = pRootElement->FindAll(TreeScope_Subtree, pCondition, &pElementFound);
    if (S_OK != hr)
    {
        printf("CreatePropertyCondition error: %d\n", GetLastError());
    }
    int eleCount;
    pElementFound->get_Length(&eleCount);
    for (int i = 0; i <= eleCount; i++)
    {
        IUIAutomationElement* pElement;
        hr = pElementFound->GetElement(i, &pElement);
        if (S_OK != hr)
        {
            printf("CreatePropertyCondition error: %d\n", GetLastError());
        }
        hr = pElement->get_CurrentName(&name);
        if (S_OK != hr)
        {
            printf("CreatePropertyCondition error: %d\n", GetLastError());
        }
        wprintf(L"Control Name: %s\n", name);
        hr = pElement->get_CurrentClassName(&name);
        if (S_OK != hr)
        {
            printf("CreatePropertyCondition error: %d\n", GetLastError());
        }
        wprintf(L"Class Name: %s\n", name);
    }
}

int main()
{
    HRESULT hr = CoInitializeEx(NULL, COINITBASE_MULTITHREADED | COINIT_DISABLE_OLE1DDE);
    if (S_OK != hr)
    {
        printf("CoInitializeEx error: %d\n", GetLastError());
        return 1;
    }

    hr = CoCreateInstance(CLSID_CUIAutomation, NULL, CLSCTX_INPROC_SERVER, IID_IUIAutomation, reinterpret_cast<void**>(&pClientUIA));
    if (S_OK != hr)
    {
        printf("CoCreateInstance error: %d\n", GetLastError());
        return 1;
    }


    HWND hwnd = (HWND)0x00030AF6;
    if (hwnd == NULL)
    {
        printf("FindWindow error: %d\n", GetLastError());
        return 1;
    }

    hr = pClientUIA->ElementFromHandle(hwnd, &pRootElement);
    if (S_OK != hr)
    {
        printf("ElementFromHandle error: %d\n", GetLastError());
        return 1;
    }

    FindControl(UIA_TextControlTypeId);
}

 

posted @ 2020-05-15 17:01  strive-sun  阅读(1265)  评论(0编辑  收藏  举报