Search code examples
c++winapimicrosoft-ui-automation

UIAutomation GetTopLevelWindowByName


Trying to follow the example found here:

https://learn.microsoft.com/en-us/windows/win32/winauto/uiauto-howto-find-ui-elements

WCHAR window_name[250] = L"tools";
IUIAutomationElement *window = GetTopLevelWindowByName(window_name);

IUIAutomationElement* GetTopLevelWindowByName(LPWSTR windowName)
{
    if (windowName == NULL)
        return NULL;

    CComPtr<IUIAutomation> g_pAutomation;

    VARIANT varProp;
    varProp.vt = VT_BSTR;
    varProp.bstrVal = SysAllocString(windowName);
    if (varProp.bstrVal == NULL)
        return NULL;

    IUIAutomationElement* pRoot        = NULL;
    IUIAutomationElement* pFound       = NULL;
    IUIAutomationCondition* pCondition = NULL;

    // Get the desktop element. 
    HRESULT hr = g_pAutomation->GetRootElement(&pRoot);
    if (FAILED(hr) || pRoot == NULL)
        goto cleanup;

    // Get a top-level element by name, such as "Program Manager"
    hr = g_pAutomation->CreatePropertyCondition(UIA_NamePropertyId, varProp, &pCondition);
    if (FAILED(hr))
        goto cleanup;

    pRoot->FindFirst(TreeScope_Children, pCondition, &pFound);

cleanup:
    if (pRoot != NULL)
        pRoot->Release();

    if (pCondition != NULL)
        pCondition->Release();

    VariantClear(&varProp);
    return pFound;
}

But the application is crashing at the line HRESULT hr = g_pAutomation->GetRootElement(&pRoot);

With the error:

File: C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\VC\Tools\MSVC\14.28.29333\atlmfc\include\atlcomcli.h
Line: 204

Expression: p!=0

What I'm trying is, learn how to iterate through the elements like name, description, etc of the given window.


Solution

  • You must create g_pAutomation, it cannot be null, for example like this:

    CoCreateInstance(
        __uuidof(CUIAutomation),
        NULL,
        CLSCTX_ALL,
        _uuidof(IUIAutomation),
        (void**)&g_pAutomation);