delphi回调函数

 

文章来源:
http://anony3721.blog.163.com/blog/static/5119742010866050589/

 

一.主单元

 1 unit UnMain;
 2 
 3 interface
 4 
 5 uses
 6   Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
 7   Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Imaging.jpeg,
 8   Vcl.ExtCtrls;
 9 
10 type
11   TFrmMain = class(TForm)
12     Edit1: TEdit;
13     Button1: TButton;
14     Image1: TImage;
15     procedure Button1Click(Sender: TObject);
16   private
17     { Private declarations }
18     procedure Test(str:string); {定义一个用于回调的过程}
19   public
20     { Public declarations }
21   end;
22 
23 var
24   FrmMain: TFrmMain;
25 
26 implementation
27 {引用子窗体单元}
28 uses UnChild;
29 {$R *.dfm}
30 
31 procedure TFrmMain.Button1Click(Sender: TObject);
32 begin
33   {调用Unit2的接口方法}
34   CallUnit2(test);
35 end;
36 
37 {回调过程的实现部分}
38 procedure TFrmMain.test(str: string);
39 begin
40   {将str值副给Edit1}
41   Edit1.Text:=str;
42 end;
43 
44 end.
View Code

二.子单元

 1 unit UnChild;
 2 
 3 interface
 4 
 5 uses
 6   Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
 7   Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;
 8 
 9 type
10    TFuncCallBack = procedure(str:string) of object;
11   TFrmChild = class(TForm)
12     Edit1: TEdit;
13     Button1: TButton;
14     procedure Button1Click(Sender: TObject);
15   private
16   public
17     {定义一个回调函数类型的变量}
18     aFuncCallBack:TFuncCallBack;
19   end;
20    {提供给Unit1调用的接口方法,注意里面的参数的类型}
21     procedure CallUnit2(FuncCallBack:TFuncCallBack);
22 var
23   FrmChild: TFrmChild;
24 
25 implementation
26 
27 {$R *.dfm}
28 {接口方法的实现部分}
29 procedure CallUnit2(FuncCallBack:TFuncCallBack);
30 begin
31   Application.CreateForm(TFrmChild,FrmChild);
32   {将参数赋值给FuncCallBack}
33   FrmChild.aFuncCallBack:=FuncCallBack;
34   FrmChild.ShowModal;
35 end;
36 
37 procedure TFrmChild.Button1Click(Sender: TObject);
38 begin
39   {当点击Form2的按钮时将Form2中的Edit的值传递给了Form1中的Edit}
40   {是不是很神奇?我并没有uses Unit1,但却改变了Form1中Edit的Text属性}
41   aFuncCallBack(Edit1.Text);
42   ModalResult:=mrOk;
43 end;
44 
45 end.
View Code

 

posted on 2016-09-05 17:43  疯狂delphi  阅读(1632)  评论(0编辑  收藏  举报

导航