如何给动态生成的控件的事件加参数?(50分)

  • 主题发起人 主题发起人 小天
  • 开始时间 开始时间

小天

Unregistered / Unconfirmed
GUEST, unregistred user!
如:
procedure TForm1.myclick(Sender: TObject;s:string);
begin
showmessage(s);
end;

procedure TForm1.Button1Click(Sender: TObject);
var btn:TButton;
begin
btn:=Tbutton.Create(nil);
btn.Parent:=Form1;
btn.Left:=20;
btn.Top:=70;
btn.Caption:='New';
btn.OnClick:=myclick('sss'); //这里怎么写才对昵?
end;
 
按钮的OnCick事件的类型为:
type TNotifyEvent = procedure(sender:Tobject) of object;
因此,myclick过程也应该是这种过程,不能加加参数。
 
这样做肯定不行了,

 
var
s: string;

procedure TForm1.myclick(Sender: TObject;);
begin
showmessage(s);
end;

procedure TForm1.Button1Click(Sender: TObject);
var btn:TButton;
begin
btn:=Tbutton.Create(nil);
btn.Parent:=Form1;
btn.Left:=20;
btn.Top:=70;
btn.Caption:='New';
s:='sss';
btn.OnClick:=myclick;
end;
 
lollman,在我的程序中全局变量没有作用,能用的话我早就用了
 
好象DELPHI中基类中有两个方法一个叫做MethodAddress一个叫做MethodName可能它是你需
要的.
 
那有没有
procedure myclick(Sender:TObject);
之类的事件数组定义方法呢?
 
给你一个自定义控件,用它便OK

type TMyNotifyEvent = procedure(sender:Tobject; Str: String) of object;
type
TmyButton = class(TButton)
private
FOnMyClick: TMyNotifyEvent;
{ Private declarations }
protected
{ Protected declarations }
public
{ Public declarations }
published
property OnMyClick: TMyNotifyEvent read FOnMyClick write FOnMyClick;
{ Published declarations }
end;
 
type TMyNotifyEvent = procedure(sender:Tobject; Str: String) of object;
type
TmyButton = class(TButton)
private
FOnMyClick: TMyNotifyEvent;
{ Private declarations }
protected
{ Protected declarations }
public
{ Public declarations }
published
property OnMyClick: TMyNotifyEvent read FOnMyClick write FOnMyClick;
{ Published declarations }
end;
type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form1: TForm1;

implementation

{$R *.DFM}

procedure TmyButtonOnMyClick(sender:Tobject; Str: String);
begin
showmessage(Str);
end;

procedure TForm1.Button1Click(Sender: TObject);
var btn:TmyButton;
begin
btn:=Tmybutton.Create(nil);
btn.Parent:=Form1;
btn.Left:=20;
btn.Top:=70;
btn.Caption:='New';
btn.OnMyClick(Sender,'123'); //执行到这儿出错,请问为什么?
end;
 
晕倒!
为什么要这样做呢?
 
LanFairy 给出的类,没有触发 Myclick 事件的代码啊,应该不行的。小天那样调用时
OnMyClick 时 OnMyclick 还是 nil, 当然出错。把参数写成 public 的属性:
type
TmyButton = class(TButton)
private
FMsg: string;
public
property Msg: string read FMsg write FMsg;
end;

TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
procedure MyClick(sender:Tobject);

end;

var
Form1: TForm1;

implementation

{$R *.DFM}

procedure TForm1.MyClick(sender:Tobject);
begin
showmessage((Sender as TMyButton).Msg);
end;

procedure TForm1.Button1Click(Sender: TObject);
var btn:TmyButton;
begin
btn:=Tmybutton.Create(Self);
btn.Parent:=Self;
btn.Left:=20;
btn.Top:=70;
btn.Caption:='New';
btn.Msg := '123';
btn.OnClick := MyClick;
end;
这样间接地传递参数。
 
多人接受答案了。
 
后退
顶部