Title: How to assign a component-event at runtime
Question: Sometimes you need to assign an event in code...
Answer:
type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
procedure MyEvent(Sender: TObject);
private
public
end;
procedure TForm1.Button1Click(Sender: TObject);
var hBtn: TButton;
begin
hBtn := TButton.Create(Application);
hBtn.Parent := Form1;
hBtn.Caption := 'New Button';
hBtn.OnClick := MyEvent;
hBtn.show;
end;
procedure TForm1.MyEvent(Sender: TObject);
begin
ShowMessage((Sender as TButton).Caption);
end;