nick
nick

Reputation: 3239

Assign event listener to dynamically created TPanel in Delphi

I created a TPanel component like this:

procedure TVistaVehiculo.CrearMenu(Name: string);
var
  Panel : TPanel;
begin
  Panel := TPanel.Create(VistaVehiculo);
  Panel.Parent := VistaVehiculo.Sidebar;
  Panel.Width := VistaVehiculo.Sidebar.Width;
  Panel.Height := 40;
  Panel.Caption := Name;
  Panel.BevelInner := TBevelCut.bvNone;
  Panel.BevelOuter := TBevelCut.bvNone;
  Panel.BevelKind := TBevelKind.bkNone;
end;

Now, I want to attach an event listener to this panel and pass the object as a parameter.

So then I create a procedure like this:

procedure TVistaVehiculo.ClickOnMenu(Sender: TPanel);
begin
    Sender.Caption := 'Clicked'; //for example
end;

How can I do this?

Sorry if the question is dumb - I'm pretty new to Delphi

Upvotes: 2

Views: 815

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 596833

procedure TVistaVehiculo.CrearMenu(Name: string);
var
  Panel : TPanel;
begin
  Panel := TPanel.Create(VistaVehiculo);
  Panel.Parent := VistaVehiculo.Sidebar;
  Panel.Width := VistaVehiculo.Sidebar.Width;
  Panel.Height := 40;
  Panel.Caption := Name;
  Panel.BevelInner := TBevelCut.bvNone;
  Panel.BevelOuter := TBevelCut.bvNone;
  Panel.BevelKind := TBevelKind.bkNone;
  Panel.OnClick := ClickOnMenu; // <-- add this!
end;

procedure TVistaVehiculo.ClickOnMenu(Sender: TObject); // <-- must be TObject!
begin
  TPanel(Sender).Caption := 'Clicked';
end;

Upvotes: 4

Related Questions