refactor: Simplify implementation of WindowEnumerator

This commit is contained in:
Nikolaos Georgiou 2022-09-06 20:40:52 +02:00
parent 91f81c941b
commit fa7f696a53

View File

@ -8,59 +8,37 @@ uses
Windows; Windows;
type type
{ An object method that accepts a HWND }
TWndConsumer = procedure (Wnd: HWND) of object; TWndConsumer = procedure (Wnd: HWND) of object;
{ Calls the given consumer for every child window of the given window }
procedure EnumerateChildWindows(Wnd: HWND; Consumer: TWndConsumer); procedure EnumerateChildWindows(Wnd: HWND; Consumer: TWndConsumer);
implementation implementation
type type
TWindowEnumerator = class { Wrapper structure to hold the object procedure and pass it as a pointer }
private PWrapper = ^TWrapper;
FWnd: HWND; TWrapper = record
FConsumer: TWndConsumer; Consumer: TWndConsumer;
class function MyEnumChildrenProc(Wnd: HWND; Lp: LPARAM): BOOL; static; stdcall; end;
procedure Add(Wnd: HWND);
public { Callback for Windows' EnumChildWindows }
constructor Create(Wnd: HWND; Consumer: TWndConsumer); function MyEnumChildrenProc(Wnd: HWND; Lp: LPARAM): BOOL; stdcall;
procedure Run; var
Wrapper: PWrapper;
begin
Wrapper := PWrapper(Lp);
Wrapper^.Consumer(Wnd);
Result := True;
end; end;
procedure EnumerateChildWindows(Wnd: HWND; Consumer: TWndConsumer); procedure EnumerateChildWindows(Wnd: HWND; Consumer: TWndConsumer);
var var
Enumerator: TWindowEnumerator; Wrapper: TWrapper;
begin begin
Enumerator := TWindowEnumerator.Create(Wnd, Consumer); Wrapper.Consumer := Consumer;
try EnumChildWindows(Wnd, @MyEnumChildrenProc, LPARAM(@Wrapper));
Enumerator.Run;
finally
Enumerator.Free;
end;
end;
constructor TWindowEnumerator.Create(Wnd: HWND; Consumer: TWndConsumer);
begin
FWnd := Wnd;
FConsumer := Consumer;
end;
procedure TWindowEnumerator.Run;
begin
EnumChildWindows(FWnd, @TWindowEnumerator.MyEnumChildrenProc, LPARAM(Self));
end;
class function TWindowEnumerator.MyEnumChildrenProc(Wnd: HWND; Lp: LPARAM): BOOL; static; stdcall;
var
Me: TWindowEnumerator;
begin
Me := TWindowEnumerator(Lp);
Me.Add(Wnd);
Result := True;
end;
procedure TWindowEnumerator.Add(Wnd: HWND);
begin
FConsumer(wnd);
end; end;
end. end.