@vieuallab assigning events to controls can also be done recursively passing the event address as a parameter and going through the lis of child controls of every child control.
If the event code is always the same For every control it simplifies it a lot.
Do you mean the
Controls property? Yes, you can do that if the parent control (i.e. the one that holds the list of child controls) is of class
TWinControl (or a derivative), for example
TPanel (as in the example). But then you have to add code to select (filter) controls according to some criterion (which the programmer sets). Otherwise, each control present on the form (or other visual container) will get a pointer to the
OnClick event handler. And there can be more controls on the form than those used for navigation. It all depends on whether the navigation panel has a fixed number of controls or if they are added dynamically at runtime. I am attaching a modified project for assigning events to controls.
unit Unit1;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, ExtCtrls, StdCtrls;
type
{TForm1}
TForm1 = class(TForm)
LabelA: TLabel;
LabelB: TLabel;
MemoInfo: TMemo;
PanelOne: TPanel;
PanelFour: TPanel;
PanelTwo: TPanel;
PanelThree: TPanel;
PanelNavigation: TPanel;
procedure FormCreate(Sender: TObject);
procedure PanelNavigationClick(Sender: TObject);
private
procedure AssignClickHandler(AParent: TWinControl; const AHandler: TNotifyEvent);
public
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
{TForm1}
procedure TForm1.FormCreate(Sender: TObject);
begin
{assigning the click handler to the events in the controls}
AssignClickHandler(PanelNavigation, @PanelNavigationClick);
end;
procedure TForm1.AssignClickHandler(AParent: TWinControl; const AHandler: TNotifyEvent);
var
i: Integer;
LAnyControl: TControl;
LWinControl: TWinControl;
begin
{assigning the "PanelNavigationClick" event handler to the "OnClick" event in
all child controls belonging to the navigation panel}
for i := 0 to AParent.ControlCount - 1 do
begin
LAnyControl := AParent.Controls[i];
LAnyControl.OnClick := AHandler;
{if the selected control is of the TWinControl class, it can have sub-controls
(i.e. it has the "Controls" property), but if it is of the "TGraphicControl"
class (such as "TLabel"), then this is not possible}
if LAnyControl is TWinControl
then
begin
LWinControl := LAnyControl as TWinControl;
if LWinControl.ControlCount > 0
then AssignClickHandler(Self, AHandler);
end;
end;
end;
procedure TForm1.PanelNavigationClick(Sender: TObject);
var
LControl: TControl;
LText: String;
begin
{control click handling}
LText := 'Clicked: ' + Sender.ClassName;
if Sender is TControl
then
begin
LControl := Sender as TControl;
LText := LText + ', ' + LControl.Name;
end;
MemoInfo.Lines.Add(LText);
end;
end.