Adding events to a TList.

Adding a procedural type to a TList, or TStringList

Here is the code I used to achieve it:

unit Unit1;



  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,



  TForm1 = class(TForm)

    ListBox1: TListBox;

    Button1: TButton;

    procedure Button1Click(Sender: TObject);

    procedure ListBox1Click(Sender: TObject);


    { Private declarations }


    { Public declarations }



  Form1: TForm1;


{$R *.DFM}


  TEventObject = class


    //Change here (For beginers only)

    FEvent: TNotifyEvent;


    //Change Here (For beginers only)

    property Event: TNotifyEvent read FEvent write FEvent;


//To add to the list

procedure TForm1.Button1Click(Sender: TObject);

var A: TEventObject;


  A := TEventObject.Create;

  A.Event := Button1Click; // or any TNotifyEvent

  ListBox1.Items.AddObject('Button1Click', A);


//To call the event

procedure TForm1.ListBox1Click(Sender: TObject);


  if ListBox1.ItemIndex<> -1 then




(For beginers only) if you want to addapt this code to any other procedure, and/or procedural types, just change the sections that state change here. How does it works, quite easy friend it creates an object whose sole purpose is to hold the event until called. In this case objects are not freed anywhere, since it was just a demostration in real life you will have to free the objects somewhere (onClose, OnCloseQuery of a form, or in a destructor)

(For criticist) In my case I just wanted a list of events of a fixed form, I know you will yell that RTTI could be a better solution, perhaps it is but I dont know well how RTTI works so I resorted to a object to hold the event, and since it is perfectly valid, perhaps the extra memory is woth it.


Share this article!

Follow us!

Find more helpful articles: