delphi回调函数
文章来源:
http://anony3721.blog.163.com/blog/static/5119742010866050589/
一.主单元
unit UnMain; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Imaging.jpeg, Vcl.ExtCtrls; type TFrmMain = class(TForm) Edit1: TEdit; Button1: TButton; Image1: TImage; procedure Button1Click(Sender: TObject); private { Private declarations } procedure Test(str:string); {定义一个用于回调的过程} public { Public declarations } end; var FrmMain: TFrmMain; implementation {引用子窗体单元} uses UnChild; {$R *.dfm} procedure TFrmMain.Button1Click(Sender: TObject); begin {调用Unit2的接口方法} CallUnit2(test); end; {回调过程的实现部分} procedure TFrmMain.test(str: string); begin {将str值副给Edit1} Edit1.Text:=str; end; end.
二.子单元
unit UnChild; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls; type TFuncCallBack = procedure(str:string) of object; TFrmChild = class(TForm) Edit1: TEdit; Button1: TButton; procedure Button1Click(Sender: TObject); private public {定义一个回调函数类型的变量} aFuncCallBack:TFuncCallBack; end; {提供给Unit1调用的接口方法,注意里面的参数的类型} procedure CallUnit2(FuncCallBack:TFuncCallBack); var FrmChild: TFrmChild; implementation {$R *.dfm} {接口方法的实现部分} procedure CallUnit2(FuncCallBack:TFuncCallBack); begin Application.CreateForm(TFrmChild,FrmChild); {将参数赋值给FuncCallBack} FrmChild.aFuncCallBack:=FuncCallBack; FrmChild.ShowModal; end; procedure TFrmChild.Button1Click(Sender: TObject); begin {当点击Form2的按钮时将Form2中的Edit的值传递给了Form1中的Edit} {是不是很神奇?我并没有uses Unit1,但却改变了Form1中Edit的Text属性} aFuncCallBack(Edit1.Text); ModalResult:=mrOk; end; end.
http://www.cnblogs.com/FKdelphi/p/5843104.html
请发表评论