The code uses IUIAutomation::ElementFromPoint for quick test. Let the mouse hover over the scroll bar to retrieve the UI Automation element.
#include <Windows.h>
#include <UIAutomation.h>
#include <wchar.h>
int Element(IUIAutomation* automation)
{
// Get the element under the cursor
// Use GetPhysicalCursorPos to interact properly with
// High DPI
POINT pt;
GetPhysicalCursorPos(&pt);
IUIAutomationElement* pAtMouse;
HRESULT hr = automation->ElementFromPoint(pt, &pAtMouse);
if (FAILED(hr))
return hr;
// Get the element's name and print it
BSTR name;
hr = pAtMouse->get_CurrentName(&name);
if (SUCCEEDED(hr))
{
wprintf(L"Element's Name: %s \n", name);
SysFreeString(name);
//IUIAutomationValuePattern* pattern;
//pAtMouse->GetCurrentPatternAs(UIA_ValuePatternId, IID_IUIAutomationValuePattern,(void**)&pattern);
IUIAutomationLegacyIAccessiblePattern* pattern;
//pAtMouse->GetCurrentPatternAs(UIA_LegacyIAccessiblePatternId, IID_IUIAutomationLegacyIAccessiblePattern,(void**)&pattern);
pAtMouse->GetCurrentPatternAs(UIA_LegacyIAccessiblePatternId, IID_PPV_ARGS(&pattern));
//TODO
BSTR url = nullptr;
pattern->get_CurrentValue(&url);
DWORD state = 0;
pattern->get_CurrentState(&state);
BSTR elename = nullptr;
pattern->get_CurrentName(&elename);
DWORD role = 0;
pattern->get_CurrentRole(&role);
//wprintf(L"Element's ValuePattern: %s \n", url);
SysFreeString(url);
SysFreeString(elename);
}
IUIAutomationScrollPattern* pattern1;
if (pAtMouse->GetCurrentPatternAs(UIA_ScrollPatternId, IID_PPV_ARGS(&pattern1)) == S_OK)
{
wprintf(L"Success! \n");
if (pattern1)
{
BOOL b{};
pattern1->get_CurrentVerticallyScrollable(&b);
double size;
pattern1->get_CurrentVerticalViewSize(&size);
double p;
pattern1->get_CurrentVerticalScrollPercent(&p);
pattern1->SetScrollPercent(0,p+1.0);
wprintf(L"get_CurrentVerticalViewSize:%f get_CurrentVerticalScrollPercent:%f\n", size, p);
}
}
// Get the element's Control Type (in the current languange)
// and print it
BSTR controlType;
hr = pAtMouse->get_CurrentLocalizedControlType(&controlType);
if (SUCCEEDED(hr))
{
wprintf(L"Element's Control Type: %s \n", controlType);
SysFreeString(controlType);
}
// Clean up our COM pointers
pAtMouse->Release();
return hr;
}
int main(int argc, TCHAR* argv[])
{
// Initialize COM and create the main Automation object
IUIAutomation* g_pAutomation;
CoInitialize(NULL);
HRESULT hr = CoCreateInstance(__uuidof(CUIAutomation), NULL,
CLSCTX_INPROC_SERVER, __uuidof(IUIAutomation),
(void**)&g_pAutomation);
if (FAILED(hr))
return (hr);
bool quit = false;
while (!quit)
{
SHORT leftControlMod = GetAsyncKeyState(VK_LCONTROL);
if (leftControlMod != 0)
{
Element(g_pAutomation);
Sleep(100);
}
quit = GetAsyncKeyState(VK_ESCAPE);
}
g_pAutomation->Release();
CoUninitialize();
return 0;
}