Delphi: How to assign dynamically an event handler without overwriting the existing event handler

delphievent handling

I need to loop through Components and assign an event handler (for example Dynamically assigning OnClick event for all TButton to

ShowMessage('You clicked on ' + (Sender as TButton).Name);

The problem is that in some cases I already assigned the TButton OnClick event.

Is there a way to solve the problem?

Let's imagine I have Button1 for which the harcoded onclick event handler is:

ShowMessage('This is Button1');

After my "parsing" I would like that the full event handler for Button1 becomes:

ShowMessage('This is Button1'); // design time event handler code
ShowMessage('You clicked on ' + (Sender as TButton).Name); // runtime added

Note: I am looking for a soliution that allows me to use TButton as it is without inheriting from it.

Best Answer

you could look for an assignment of OnClick before overwriting it, persist this and use it in your new handler - basically chaining the events.

Something like this:

  var original : TNotifyEvent;

  original := Component.OnClick;
  Component.OnClick := NewMethod;

and then in your NewMethod:

  if assigned(original) then original(Sender);

you'll likely not want a single original variable but instead hold a collection keyed on the component.

Related Topic