picture

TNotifyEvent. OnClick Example for Delphi.

Listening to events in Delphi is pretty easy. In following I’d like to introduce two ways to list to events. Consider following example:


type
  TForm1 = class(TForm)
    MyButton1: TButton;
    procedure FormCreate(Sender: TObject);
  private
    { Private-Deklarationen }
    procedure MyBtnClick(Sender: TObject);
  public
    { Public-Deklarationen }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.MyButtonClick(Sender: TObject);
begin
  ShowMessage('Button is clicked!');
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  MyButton1 := TButton.Create(Form1);
  MyButton1.Parent := Form1;
  MyButton1.OnClick := MyButtonClick;
end;

In this simple case MyButtonClick is a class method. The way it’s used in the example above is quite usual. But what to do if you need to use some method to handle OnClick event, which is defined outside the class(external function)? In this situation you have to wrap up your method by a record:


type
  TMethodPointer = packed record
    pMethod: Pointer;
    pObject: TObject;
end;

After this you can add your event handler, using casting to TNotifyEvent like this:


methodPointer.pMethod := @MyOnClickMethod;
methodPointer.pObject := nil;
MyButton1.OnClick :=  TNotifyEvent(methodPointer);

Leave a Reply

You must be logged in to post a comment.