UIAutomation GetTopLevelWindowByName 方法

UIAutomation GetTopLevelWindowByName

尝试按照此处找到的示例进行操作:

https://docs.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;
}

但应用程序在第 HRESULT hr = g_pAutomation->GetRootElement(&pRoot);

行崩溃

出现错误:

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

Expression: p!=0

我正在尝试的是,学习如何遍历给定 window.

的名称、描述等元素

必须创建g_pAutomation,不能为空,例如:

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