2008. szeptember 4., csütörtök

How to define a custom event


Problem/Question/Abstract:

Does anyone have a good example for creating a custom event? I want a TDataModule subclass to fire a custom event, and then a TForm subclass to detect this event and perform some action.

Answer:

First you define the event and create an event property on the datamodule to refer to this event:

TCustomEvent = procedure(Sender: TObject; Var1: integer; Var2: string) of object;

TMyDataModule = class(TDataModule)
private
  { Private declarations }
  FCustomEvent: TCustomEvent;
public
  { Public declarations }
  property CustomEvent: TCustomEvent read FCustomEvent write FCustomEvent;
end;

Next, in some event handler on the form (like the OnCreate) you create a method that matches the event definition and then you programmatically assign it to the datamodule's event property:

type
  TForm1 = class(TForm)
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
    procedure CustomEvent(Sender: TObject; Var1: Integer; Var2: string);
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

uses Unit2;

{$R *.DFM}

procedure TForm1.CustomEvent(Sender: TObject; Var1: Integer; Var2: string);
begin
  ShowMessage('Hello');
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  MyDataModule.CustomEvent := CustomEvent;
end;

end.

Nincsenek megjegyzések:

Megjegyzés küldése