如何通过悬停光标来获取 UIAutomationElement 的 NamePropertyId?

How do you get the NamePropertyId of a UIAutomationElement by hovering the cursor?

我正在尝试使用 UIAutomation 构建我自己的屏幕 reader。我希望我的程序 return 光标指向的元素的 NameProperty

这是我到目前为止所做的;这只是示例代码:

#include <iostream>
#include <windows.h>
#include <UIAutomation.h>

const int MAX_WND_TEXT = 60;

IUIAutomation *automation = NULL;

BOOL InitializeUIAutomation(IUIAutomation **pAutomation)
{
    CoInitialize(NULL);
    HRESULT hr = CoCreateInstance(__uuidof(CUIAutomation), NULL,
        CLSCTX_INPROC_SERVER,
        __uuidof(IUIAutomation), (void**)pAutomation);
    return (SUCCEEDED(hr));
}

int main()
{
    POINT p;

    IUIAutomationElement *elem;
    wchar_t wndName[MAX_WND_TEXT];
    BOOL stat = InitializeUIAutomation(&automation);
    while (true)
    {
        if (stat)
        {
            GetCursorPos(&p);
            HRESULT hr = automation->ElementFromPoint(p, &elem);
            if (SUCCEEDED(hr))
            {
                HRESULT hr = elem->GetCurrentPropertyValue(UIA_NamePropertyId,
                    (VARIANT*)wndName);
                if (SUCCEEDED(hr))
                    std::cout << wndName << std::endl;
                else
                    wndName[0] = '[=10=]';
            }
            else
                std::cout << "No element selected." << std::endl;

            Sleep(100);
            elem->Release();
        }
    }
    automation->Release();
    CoUninitialize();
    return 0;
}

现在的问题是我无法打印出我想要的值。该程序只输出一个特定的十六进制数。而且我仍然是 UIAutomation 的初学者,所以我仍然迷路。

你能帮助我或给我提示如何解决我的问题吗?

使用此代码解决了我的问题。

#include <iostream>
#include <string>
#include <Windows.h>
#include <UIAutomation.h>

BOOL InitializeUIAutomation(IUIAutomation **automation)
{
    CoInitialize(NULL);
    HRESULT hr = CoCreateInstance(__uuidof(CUIAutomation), NULL,
        CLSCTX_INPROC_SERVER, __uuidof(IUIAutomation),
        (void**)automation);
    return (SUCCEEDED(hr));
}

int main()
{
    IUIAutomation *automation = NULL;
    IUIAutomationElement *elem = NULL;
    BOOL stat = InitializeUIAutomation(&automation);
    POINT mousePt;
    BSTR elemName = NULL;
    if (stat)
    {
        while(true)
        {
            GetCursorPos(&mousePt);
            HRESULT hr = automation->ElementFromPoint(mousePt, &elem);
            if (SUCCEEDED(hr) && elem != NULL)
            {
                elem->get_CurrentName(&elemName);
                std::wstring ws(elemName, SysStringLen(elemName));
                std::wcout << ws << std::endl;
            }
            SysFreeString(elemName);
            elem->Release();
            Sleep(200);
        }
    }
    automation->Release();
    CoUninitialize();

    return 0;
}

打印的十六进制数字毕竟是 BSTR header。通过将 BSTR 转换为 wstring 来解决我的问题。