Your mistake is in the way that you pass the window handle to ElementFromHandle
. You are meant to pass an HWND
. Instead you pass the address of an HWND
.
The function should really be:
function ElementFromHandle(hwnd: HWND;
out element: IUIAutomationElement): HResult; stdcall;
You should remove the call to New
and instead do:
var
window: HWND;
....
window := HWND($1094E);
Then call the function like this:
if Succeeded(UIAuto.ElementFromHandle(window, element)) then
....
Perhaps your biggest fundamental problem is the complete absence of error checking. I think you need to adjust your mindset to realise that these API calls will not raise exceptions. They report failure through their return value. You must check every single API call for failure.
One common way to do that is to convert HRESULT
values to exceptions in case of failure with calls to OleCheck
. For example:
var
UIAuto: IUIAutomation;
element: IUIAutomationElement;
value: WideString;
window: HWND;
....
window := HWND($1094E);
SetForegroundWindow(window);
ShowWindow(window, SW_SHOW);
UIAuto := CoCUIAutomation.Create;
OleCheck(UIAuto.ElementFromHandle(window, element));
OleCheck(element.Get_CurrentName(value));
ShowMessage('found -' + value);