首页 > 解决方案 > 获取光标下的 HWND 以与 UIAutomation 一起使用

问题描述

我正在尝试获取有关光标下当前窗口的信息,当我手动指定 时,我得到了该功能hwnd,如何hwnd从鼠标下的当前窗口中获取?

#include <UIAutomation.h>

POINT p;
GetCursorPos(&p);CComPtr<IAccessible> pAcc;


VARIANT varChild;
if (SUCCEEDED(AccessibleObjectFromWindow((HWND)hwnd, 
    OBJID_WINDOW,IID_IAccessible, reinterpret_cast<void**>(&pAcc))))
{
    CComBSTR bstrName, bstrValue, bstrDescription;
    varChild.vt = VT_I4;
    varChild.lVal = CHILDID_SELF;
    if (SUCCEEDED(pAcc->get_accName(varChild, &bstrName)))
        auto name = bstrName.m_str;

    if (SUCCEEDED(pAcc->get_accValue(varChild, &bstrValue)))
        auto value = bstrValue.m_str;

    if (SUCCEEDED(pAcc->get_accValue(varChild, &bstrDescription)))
        auto description = bstrDescription.m_str;

}

标签: c++winapimicrosoft-ui-automation

解决方案


您正在寻找的是IUIAutomation::ElementFromPoint 方法

这是一个小型控制台应用程序(带有 Visual Studio ATL 的 C++),它连续显示光标下自动化元素的名称和窗口句柄(如果有):

// needs
//#include <UIAutomationCore.h>
//#include <UIAutomationClient.h>

int main()
{
    if (SUCCEEDED(CoInitialize(NULL)))
    {
        CComPtr<IUIAutomation> automation;
        if (SUCCEEDED(automation.CoCreateInstance(CLSID_CUIAutomation8))) // or CLSID_CUIAutomation
        {
            do
            {
                POINT pos;
                if (GetCursorPos(&pos))
                {
                    CComPtr<IUIAutomationElement> element;
                    if (SUCCEEDED(automation->ElementFromPoint(pos, &element)))
                    {
                        CComBSTR name;
                        element->get_CurrentName(&name);
                        wprintf(L"name: %s\n", name);

                        UIA_HWND hwnd;
                        element->get_CurrentNativeWindowHandle(&hwnd);
                        wprintf(L"hwnd: %p\n", hwnd);
                    }
                }
                Sleep(500);
            } while (TRUE);
        }
    }

    CoUninitialize();
    return 0;
}

推荐阅读