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

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

本文关键字:UIAutomationElement NamePropertyId 获取 何通过 悬停 光标      更新时间:2023-10-16

我正在尝试使用UIAutomation构建自己的屏幕阅读器。我希望我的程序返回光标指向的元素的 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] = '';
            }
            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 标头。通过将 BSTR 转换为 wstring 来解决我的问题。

相关文章:
  • 没有找到相关文章