[Lazarus] FindWindow return sequence (Windows 10)?

Bo Berglund bo.berglund at gmail.com
Mon Nov 2 08:07:14 CET 2020


I am writing utilities to enumerate windows (in Windows10) based on
the partial title. Will be used in order to find a particular set of
windows.

The function should return a list of window titles and handles to the
window. I found examples I have adapted and it is working partially..

But there is one thing I cannot understand and this is why the call to
ListWindowExtd returns the windows out of sequence.
The first handle is always larger than all following...

I thought that GetWindow(hWndTemp, GW_HWNDNEXT); would return the next
larger handle following hWndTemp, but it seems like this is not the
case. Is the result random or is there some known sequence when using
the flag GW_HWNDNEXT??

Of course I could sort the result afterwards but why? Should not
GW_HWNDNEXT do the sequencing?

I am currently using these 3 functions for the enumeration:

function GetWindowTitle(Hdl: HWND) : string;
var
  i: integer;
  cTitletemp: array [0..254] of Char;
  sTitleTemp: string;
begin
  Result := '';
  i := GetWindowText(Hdl, cTitletemp, 255);
  if i > 0 then
  begin
    sTitleTemp := cTitletemp;
    Result := Copy(sTitleTemp, 1, i);
  end;
end;

function FindWindowExtd(partialTitle : string) : HWND;
{Find handle to a window containing partialTitle}
var
  hWndTemp: hWnd;
  sTitleTemp: string;
begin
  partialTitle := LowerCase(partialTitle);
  hWndTemp := FindWindow(nil, nil); //First window???
  while hWndTemp <> 0 do
  begin
    sTitleTemp := lowercase(GetWindowTitle(hWndTemp));
    if pos(partialTitle, sTitleTemp) <> 0 then
      Break;
    hWndTemp := GetWindow(hWndTemp, GW_HWNDNEXT);
  end;
  result := hWndTemp;
end;

function ListWindowExtd(partialTitle : string) : string;
var
  hWndTemp: hWnd;
  sTitle: string;
begin
  Result := '';
  partialTitle := lowercase(partialTitle);
  hWndTemp := FindWindowExtd(partialTitle);
  if hWndTemp = 0 then exit;

  Result := IntToStr(hWndTemp) + '   '#9 + GetWindowTitle(hWndTemp);

  hWndTemp := GetWindow(hWndTemp, GW_HWNDNEXT);
  while hWndTemp <> 0 do
  begin
    sTitle := GetWindowTitle(hWndTemp);
    if pos(partialTitle, lowercase(sTitle)) <> 0 then
      Result := Result + #13 + IntToStr(hWndTemp) + '   '#9 + sTitle;
    hWndTemp := GetWindow(hWndTemp, GW_HWNDNEXT);
  end;
end;


-- 
Bo Berglund
Developer in Sweden



More information about the lazarus mailing list