In c++ one can do it this way:
HWND g_HWND=NULL;
BOOL CALLBACK EnumWindowsProcMy(HWND hwnd,LPARAM lParam)
{
DWORD lpdwProcessId;
GetWindowThreadProcessId(hwnd,&lpdwProcessId);
if(lpdwProcessId==lParam)
{
g_HWND=hwnd;
return FALSE;
}
return TRUE;
}
EnumWindowsProcMy,m_ProcessId);
(link)
The Delphi translation would be:
function GetWindowHandle(ProcessId: Cardinal): THandle;
var
hFound: THandle;
function EnumWindowsProcMy(_hwnd: HWND; ProcessId: Cardinal): BOOL; stdcall;
var
dwPid: Cardinal;
begin
GetWindowThreadProcessId(_hwnd, @dwPid);
if ProcessId = dwPid then
begin
hFound := _hwnd;
Result := False;
end
else
Result := True;
end;
begin
EnumWindows(@EnumWindowsProcMy, LPARAM(ProcessId));
Result := hFound;
end;
However it seems the "embedded" function can't acces the variable hFound correctly.
If i declare the variable outside of the function (global variable) it works fine. But that's bad by design.
One way to get around this would be to e.g. pass a record to EnumWindowProcMy and save the desired Handle there.
However i am wondering why the code doesn't work as i think i translated it correctly.