Get HWND under the cursor to use with UIAutomation
See the question and my original answer on StackOverflowWhat you're looking for is IUIAutomation::ElementFromPoint method.
Here is a small console app (C++ with Visual Studio ATL) that continuously displays the name and window handle (if any) of the automation element under the cursor:
// 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;
}