This code creates an AV:
function PAIsMainAppWindow(Wnd: THandle): Boolean;
var
ParentWnd: THandle;
ExStyle: DWORD;
begin
if IsWindowVisible(Wnd) then
begin
ParentWnd := THandle(GetWindowLongPtr(Wnd, GWLP_HWNDPARENT));
ExStyle := GetWindowLongPtr(Wnd, GWL_EXSTYLE);
Result := ((ParentWnd = 0) or (ParentWnd = GetDesktopWindow)) and
((ExStyle and WS_EX_TOOLWINDOW = 0) or (ExStyle and WS_EX_APPWINDOW <> 0));
end
else
Result := False;
end;
function PAEnumTaskWindowsProc(Wnd: THandle; List: TStrings): Boolean; stdcall;
var
Caption: array [0..1024] of Char;
begin
if PAIsMainAppWindow(Wnd) and (GetWindowText(Wnd, Caption, SizeOf(Caption)) > 0) then
List.AddObject(ExtractFileName(GetProcessNameFromWnd(Wnd)), Pointer(Wnd));
Result := True;
end;
function PAGetTaskWindowHandleFromProcess(const AProcessName: string): THandle;
var
sl: TStringList;
i: Integer;
begin
Result := 0;
sl := TStringList.Create(True); // stringlist owns objects
try
if EnumWindows(@PAEnumTaskWindowsProc, LPARAM(sl)) then
begin
for i := 0 to sl.Count - 1 do
begin
if SameText(AProcessName, sl[i]) then
begin
Result := THandle(sl.Objects[i]);
BREAK;
end;
end;
end;
finally
sl.Free; // AV!
end;
end;
ChromeHandle := PAGetTaskWindowHandleFromProcess('chrome.exe');
It is clear that the AV occurs because freeing the stringlist also destroys the function result. But how can this be avoided?