转:Delphi 回调函数及例子

时间:2023-03-31 22:05:02

http://anony3721.blog.163.com/blog/static/5119742010866050589/

{
http://anony3721.blog.163.com/blog/static/5119742010866050589/ 例子出处
}
unit Unit1; interface uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs,StdCtrls; type
TForm1 = class(TForm)
Edit1: TEdit;
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
{定义一个用于回调的过程}
procedure test(str:string);
public
{ Public declarations }
end; var
Form1: TForm1; implementation
{引用unit2}
uses unit2;
{$R *.dfm}
{回调过程的实现部分}
procedure TForm1.test(str: string);
begin
{将str值副给Edit1}
Edit1.Text:=str;
end; procedure TForm1.Button1Click(Sender: TObject);
begin
{调用Unit2的接口方法}
CallUnit2(test);
end; end.

unit Unit1

窗体文件
object Form1: TForm1
Left =
Top =
Width =
Height =
Caption = 'Form1'
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -
Font.Name = 'Tahoma'
Font.Style = []
OldCreateOrder = False
PixelsPerInch =
TextHeight =
object Edit1: TEdit
Left =
Top =
Width =
Height =
ImeName = '中文 (简体) - 搜狗拼音输入法'
TabOrder =
Text = 'Edit1'
end
object Button1: TButton
Left =
Top =
Width =
Height =
Caption = 'Button1'
TabOrder =
OnClick = Button1Click
end
end

object Form1: TForm1

unit Unit2;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls; type
{定义一个回调函数类型}
TFuncCallBack=procedure(str:string) of object;
TForm2 = class(TForm)
Edit1: TEdit;
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
{定义一个回调函数类型的变量}
aFuncCallBack:TFuncCallBack;
public
{ Public declarations }
end;
{提供给Unit1调用的接口方法,注意里面的参数的类型}
procedure CallUnit2(FuncCallBack:TFuncCallBack); var
Form2: TForm2; implementation {$R *.dfm}
{接口方法的实现部分}
procedure CallUnit2(FuncCallBack:TFuncCallBack);
begin
Application.CreateForm(TForm2,Form2);
{将参数赋值给FuncCallBack}
Form2.aFuncCallBack:=FuncCallBack; Form2.ShowModal;
end;
procedure TForm2.Button1Click(Sender: TObject);
begin
{当点击Form2的按钮时将Form2中的Edit的值传递给了Form1中的Edit}
{是不是很神奇?我并没有uses Unit1,但却改变了Form1中Edit的Text属性}
aFuncCallBack(Edit1.Text);
ModalResult:=mrOk;
end; end.

unit Unit2

窗体文件
object Form2: TForm2
Left =
Top =
Width =
Height =
Caption = 'Form2'
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -
Font.Name = 'Tahoma'
Font.Style = []
OldCreateOrder = False
PixelsPerInch =
TextHeight =
object Edit1: TEdit
Left =
Top =
Width =
Height =
ImeName = '中文 (简体) - 搜狗拼音输入法'
TabOrder =
Text = 'Edit1'
end
object Button1: TButton
Left =
Top =
Width =
Height =
Caption = 'Button1'
TabOrder =
OnClick = Button1Click
end
end

object Form2: TForm2

总结:回调 可以当做一个数据类型 使用

procedure CallUnit2(FuncCallBack:TFuncCallBack);