Author: Tomas Rutkauskas
What I am trying to achieve is to let many different objects attach to a single
event. I did it with Interfaces but I want to do it with normal methods now. My
first attempt was to simply store a pointer in a TList, but of course it did not
work. I did not think about the Code and Data pointers. My question: How do I store
methods in a list in a generic way? I do not want to specify the event type in my
base class, only in my specialized classes.
Answer:
The problem is that a TNotifyEvent is more than a pointer: it includes both data
and class information. In any case, here is a solution for you. Drop two buttons on
a form, and link the Unit1 code in below.
1 unit Unit1;
2 3 interface4 5 uses6 Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Contnrs,
7 StdCtrls;
8 9 type10 TNotifyEventObj = class11 private12 FNotifyEvent: TNotifyEvent;
13 public14 constructor Create(aNE: TNotifyEvent);
15 property NotifyEvent: TNotifyEvent read FNotifyEvent write FNotifyEvent;
16 end;
17 18 TForm1 = class(TForm)
19 Button1: TButton;
20 Button2: TButton;
21 procedure Button1Click(Sender: TObject);
22 procedure Button2Click(Sender: TObject);
23 private24 { Private declarations }25 FList: TObjectList;
26 FCount: integer;
27 procedure CountEvent(Sender: TObject);
28 public29 { Public declarations }30 constructor Create(AOwner: TComponent); override;
31 destructor Destroy; override;
32 procedure AddEvent(aNE: TNotifyEvent);
33 34 end;
35 36 var37 Form1: TForm1;
38 39 implementation40 41 {$R *.DFM}42 43 { TNotifyEventObj }44 45 constructor TNotifyEventObj.Create(aNE: TNotifyEvent);
46 begin47 FNotifyEvent := aNE;
48 end;
49 50 { TForm1 }51 52 constructor TForm1.Create(AOwner: TComponent);
53 begin54 inherited;
55 FCount := 0;
56 FLIst := TObjectList.Create;
57 end;
58 59 destructor TForm1.Destroy;
60 begin61 FList.Free;
62 inherited;
63 end;
64 65 procedure TForm1.Button1Click(Sender: TObject);
66 begin67 AddEvent(CountEvent);
68 end;
69 70 procedure TForm1.Button2Click(Sender: TObject);
71 var72 lNE: TNotifyEvent;
73 I: Integer;
74 begin75 for I := 0 to FList.Count - 1 do{ Iterate }76 begin77 lNE := TNotifyEventObj(FList[I]).NotifyEvent;
78 lNE(self);
79 end;
80 end;
81 82 procedure TForm1.AddEvent(aNE: TNotifyEvent);
83 begin84 FLIst.Add(TNotifyEventObj.Create(aNE));
85 end;
86 87 procedure TForm1.CountEvent(Sender: TObject);
88 begin89 FCount := FCount + 1;
90 Caption := IntToStr(FCount);
91 end;
92 93 end.