delphi自定义事件

来源:互联网 发布:6种网络拓扑结构图 编辑:程序博客网 时间:2024/06/03 18:27
自定义事件通常是应用程序与引用的单元文件的信息传递。下面一个例子说明,让应用程序自定义两个数的计算方式,可以为+、-、*、/等等,而内部的详细处理可以在单元文件里面实现,下面简要代码仅仅体现这种思想,具体根据实际修改:1.新建Delphi 7应用程序,单击菜单栏→File→New→Unit,在弹出的单元文件,输入以下代码:unit Unit2; interface uses   Classes;  type   TCalcEvent = procedure(AOne,AAnother: Integer) of object;  type   TCalc = class(TObject)   private     FOne,FAnother: Integer;     FOnCalc: TCalcEvent;   public     constructor Create(AOne,AAnother: Integer);     procedure StartCalc;     property OnCalc:TCalcEvent read FOnCalc write FOnCalc;   end; implementation  constructor TCalc.Create(AOne,AAnother: Integer); begin   inherited Create;   FOne := AOne;   FAnother := AAnother; end;  procedure TCalc.StartCalc; begin   if Assigned(FOnCalc) then     FOnCalc(FOne,FAnother); end; end. 2.主窗体上放置2个编辑框和一个按钮,主单元文件代码如下:unit Unit1;  interface  uses   Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,   Dialogs, StdCtrls, Unit2;  type   TForm1 = class(TForm)     btn1: TButton;     edt1: TEdit;     edt2: TEdit;     procedure btn1Click(Sender: TObject);   private     FCalc: TCalc;     procedure calc1Do(AOne,AAnother: Integer);   public     { Public declarations }   end;  var   Form1: TForm1;  implementation  {$R *.dfm}  procedure TForm1.btn1Click(Sender: TObject); begin   FCalc := TCalc.Create(StrToInt(edt1.Text),StrToInt(edt2.Text));   try     FCalc.OnCalc := calc1Do;     FCalc.StartCalc;   finally     FCalc.Free;   end; end;  procedure TForm1.calc1Do(AOne,AAnother: Integer); begin   ShowMessage(IntToStr(AOne + AAnother)); end; end. 

原创粉丝点击