pet clothing

2012年1月27日星期五

DELPHI自定义事件处理

为什么我们点击按钮,就会执行按钮的onclick事件?这个事件是怎么和我们自己的代码关联起来的。相信很多人都有这个疑问。那么我们就通过一个自定义事件来了解这里面得运行原理。以乘法运算来显示,如果乘数大于100,就提示用户,太大了。这个事件用自定义事件定义。 大家先看一下最终效果,r delphiEvent DELPHI自定义事件处理

我添加了三个文本框,一个按钮,当第一或者第二个文本框的数>100时,点求积按钮,提示Too Big 对话框。

完成自定义事件需要5步来做:

1.定义TNotifyEvent类型私有变量

FTooBig:TNotifyEvent;

FTooBig是一个指针,它可以保持事件方法的调用地址。

2.公布一个属性

published property OnTooBig:TNotifyevent read FTooBig write FTooBig;

OnTooBig这个属性用来操作FTooBig这个私有变量,因为FTooBig是个函数指针,所以但读这个变量时,也就调用了函数。

3.定义事件处理函数

procedure TooBigEvent(Sender: TObject); procedure TForm1.TooBigEvent(Sender: TObject); begin Application.MessageBox('Too Big','Test Event!',MB_OK); end;

这是当文本框数太大时执行的方法。

4. 把事件处理函数赋值给TNotifyEvent私有变量

FTooBig := TooBigEvent;

5. 当条件符合时执行事件处理函数

procedure TForm1.Button1Click(Sender: TObject);var val1 : integer; val2 : integer; res : integer;begin val1 := StrToInt(Edit1.Text); val2 := StrToInt(Edit2.Text); if(val1<100)and(val2<100) then begin res := val1*val2; Edit3.Text := IntToStr(res); end else if assigned(FTooBig) then OnTooBig(Self);end;

下面贴出全部代码:

unit Unit1;interfaceuses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls;type TForm1 = class(TForm) Edit1: TEdit; Edit2: TEdit; Edit3: TEdit; Button1: TButton; procedure TooBigEvent(Sender: TObject); procedure Button1Click(Sender: TObject); procedure FormCreate(Sender: TObject); private FTooBig:TNotifyEvent; { Private declarations } public { Public declarations } published property OnTooBig:TNotifyevent read FTooBig write FTooBig;end;var Form1: TForm1;implementation{$R *.dfm}procedure TForm1.Button1Click(Sender: TObject);var val1 : integer; val2 : integer; res : integer;begin val1 := StrToInt(Edit1.Text); val2 := StrToInt(Edit2.Text); if(val1<100)and(val2<100) then begin res := val1*val2; Edit3.Text := IntToStr(res); end else if assigned(FTooBig) then OnTooBig(Self);end;procedure TForm1.TooBigEvent(Sender: TObject);beginApplication.MessageBox('Too Big','Test Event!',MB_OK);end;procedure TForm1.FormCreate(Sender: TObject);beginFTooBig := TooBigEvent;end;end. DELPHI自定义事件处理

含浩 – who has written 205 posts on 含浩的博客.

含浩:邯郸搜搜网站长。多年从事j2ee系统研发,曾设计开发东奥会计网答疑系统,国家环保局外网数据中心报表开发,现从事.net开发工作,运营邯郸搜搜网,国外主机域名销售,discuz模板制作。

Send an Email

Tags: delphi, 自定义事件

This entry was posted on 星期四, 一月 12th, 2012 at 20:18 and is filed under delphi. You can follow any comments to this entry through the RSS 2.0 feed. You can leave a comment, or trackback.

View the original article here

标签:

0 条评论:

发表评论

订阅 博文评论 [Atom]

<< 主页