我正在尝试为我的程序编写任务栏,我需要在2个事件中添加一行代码,OnClose和OnActivate,但我的程序有100多个表单,所以我想动态地执行它。有办法吗?
语言是Delphi 7。
答案 0 :(得分:-1)
正如TLama和David Hefferman所说,继承是正确的做法,但有时候实用主义会以正确的方式胜出。所以这是一个可怕的Kludge,它将完成这项工作。
unit Unit1;
interface
uses
VCL.Forms,
System.Classes,
System.Generics.Collections;
type
TKludge = class
private
fForm: TForm;
fOnClose: TCloseEvent;
fOnActivate: TNotifyEvent;
procedure fNewOnActivate( Sender : TObject );
procedure fNewOnClose( Sender : TObject; var Action : TCloseAction );
public
property Form : TForm
read fForm;
property OnClose : TCloseEvent
read fOnClose;
property OnActivate : TNotifyEvent
read fOnActivate;
constructor Create( pForm : TForm );
end;
TKludges = class( TObjectList<TKludge> )
private
fApplication: TApplication;
procedure SetApplication(const Value: TApplication);
public
property Application : TApplication
read fApplication
write SetApplication;
end;
implementation
{ TKludge }
constructor TKludge.Create(pForm: TForm);
begin
fForm := pForm;
fOnClose := pForm.OnClose;
pForm.OnClose := fNewOnClose;
fOnActivate := pForm.OnActivate;
pForm.OnActivate := fOnActivate;
end;
procedure TKludge.fNewOnActivate(Sender: TObject);
begin
if assigned( fOnActivate ) then fOnActivate( Sender );
// my extra line
end;
procedure TKludge.fNewOnClose(Sender: TObject; var Action: TCloseAction);
begin
if assigned fOnClose then fOnClose( Sender, Action );
// my extra line
end;
{ TKludges }
procedure TKludges.SetApplication(const Value: TApplication);
var
i: Integer;
begin
fApplication := Value;
for i := 0 to fApplication.ComponentCount do
begin
if fApplication.Components[ i ] is TForm then
begin
Add( TKludge.Create( fApplication.Components[ i ] as TForm ));
end;
end;
end;
end.
创建TKludges类的实例并将Application传递给它。对于它找到的每个表单,它将用新的表单替换事件,如果它存在则调用原始事件并将你的额外行放入(只是在一分钟的注释中)。
什么使得特别可怕的是每种形式都会受到影响,包括你可能没想到的。但如果你确定......
使用风险自负!