Did you know…?

Did you know that you can get and set events with the TMethod record? Let’s assume you would like to hook an OnClose event of a form:

type
  TMyHookObject = class
  strict private
    FOldOnClose: TMethod;
    procedure OnClose(ASender: TObject; var AAction: TCloseAction);
...

procedure TMyHookObject.Init(AForm: TForm);
begin
  //Save the old event
  FOldOnClose := TMethod(AForm.OnClose);
  //Set the new one
  AForm.OnClose := OnClose;
end;

procedure TMyHookObject.OnClose(ASender: TObject; var AAction: TCloseAction);
begin
  //Call the old event
  if Assigned(FOldOnClose.Data) and Assigned(FOldOnClose.Code) then
    TCloseEvent(FOldOnClose)(ASender, AAction);
  
  //Run your own code
  ...

As you can see in the example you can easily store and call events with the help of TMethod.

This entry was posted in Uncategorized. Bookmark the permalink.