无法向手动创建的Timer控件中的ontimer传递参数(100分)

  • 主题发起人 主题发起人 ckylixj
  • 开始时间 开始时间
C

ckylixj

Unregistered / Unconfirmed
GUEST, unregistred user!
各位老师,我动态创建了多个Timer控件,并且为这些Timer控件的ontimer事件编写了一段代码(参数不同),我现在遇到的问题是没有办法将参数传递进去。

如果不传递参数,下面的代码可以编译成功
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls;
type
TForm1 = class(TForm)
Memo1: TMemo;
Button1: TButton;
procedure Button1Click(Sender: TObject);
procedure test1( sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form1: TForm1;
implementation
procedure TForm1.test1( sender: TObject);
begin
memo1.Lines.Add(FormatdateTime('yyyy-mm-dd hh:nn:ss',Now()));
end;

{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
var
time : TTimer;
begin
time := TTimer.Create(form1);
time.Interval :=2000;
time.OnTimer := test1;
time.Enabled := true;
end;

end.


如果传递了参数(ss:string),编译则报错。 [Erro]Unit1.pas(42): Incompatible type: 'TObject' and 'String
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls;
type
TForm1 = class(TForm)
Memo1: TMemo;
Button1: TButton;
procedure Button1Click(Sender: TObject);
// procedure test1( sender: TObject);
procedure test1( sender: TObject;var ss :string);
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form1: TForm1;
implementation
procedure TForm1.test1( sender: TObject;var ss :string);
begin
memo1.Lines.Add(ss + FormatdateTime('yyyy-mm-dd hh:nn:ss',Now()));
end;

{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
var
time : TTimer;
begin
time := TTimer.Create(form1);
time.Interval :=2000;
time.OnTimer := test1('aaa');
time.Enabled := true;
end;

end.
 
OnTimer是TNotifyEvent类型,只有一个TObject类型的参数,你传个
time.OnTimer := 字符串做啥?,
procedure test1( sender: TObject);
--这样声明,如果需要传字符串,在tform1的private里申明一个
 
如果只要传递一个参数可以在tform1的private里申明一个 ,我现在是动态创建了2个以上的timer空间,每个控件ontimer的过程是一样的,只是过程中的参数不一样。
 
type
TForm1 = class(TForm)
...
private
{ Private declarations }
Time1, Time2: TTime;
public
{ Public declarations }
end;

procedure TForm.FormCreate(Sender: TObject);
begin
Time1 := TTimer.Create(form1);
Time2 := TTimer.Create(form1);
Time1.Interval := 2000;
Time2.Interval := 2000;
Time1.Tag := 1;
Time2.Tag := 2;
Time1.OnTimer := test1;
Time2.OnTimer := test1;
end;

procedure TForm.FormDestroy(Sender: TObject);
begin
Time1.Free;
Time2.Free;
end;

procedure TForm.test1(Sender: TObject);
begin
case TTime(Sender).Tag of
1:
begin
...
end;
2:
begin
...
end;
end;
...
end;
 
后退
顶部