【问题标题】:Get HWND under the cursor to use with UIAutomation获取光标下的 HWND 以与 UIAutomation 一起使用
【发布时间】:2021-09-05 16:33:44
【问题描述】:

我正在尝试获取有关光标下当前窗口的信息,当我手动指定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;

}

【问题讨论】:

  • WindowFromPoint(), ChildWindowFromPoint(), RealChildWindowFromPoint()

标签: c++ winapi microsoft-ui-automation


【解决方案1】:

你要找的是IUIAutomation::ElementFromPoint method

这是一个小型控制台应用程序(带有 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;
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-07
  • 1970-01-01
  • 1970-01-01
  • 2016-09-27
  • 1970-01-01
  • 2015-09-27
相关资源
最近更新 更多