delphi 回调函数

来源:互联网 发布:淘宝打口鞋该不该买 编辑:程序博客网 时间:2024/05/16 23:33

   今天在DELPHI上随便编写了个回调函数的例子,怕以后忘了,赶紧给它给记下来,呵呵。

觉的好简单,什么都没有,只是在同一个单元内,利用了DELPHI的多线程调用回调函数,高手别见笑哈!下次肯

定要多加点东西完善滴,这次只是熟悉一下实现回调的整个过程。

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    ListBox1: TListBox;
    Button2: TButton;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;
  type PFCALLBACK = function(Param1:integer;Param2:integer):integer;stdcall;
 // 定义回调函数的类型
var
  Form1: TForm1;
  gCallBack:PFCALLBACK;
  function CBFunc(Param1:integer;Param2:integer):integer;stdcall;
implementation
//回调函数需要定义为全局
{$R *.dfm}
///实现回调函数的功能
function CBFunc(Param1:integer;Param2:integer):integer;
var i:integer;
begin
//messagebox(application.Handle,'回调函数','提示信息',mb_ok);
for i:=0 to 100 do
begin
sleep(100);
self.ListBox1.Items.Add('回调函数');
end;
end;
///
function MyThreadFunc(P:pointer):Longint;stdcall;
begin
gCallBack(0,1);//简单传个参数
end;
procedure testpro ;
var i:integer;
   hThread:Thandle;//定义一个句柄
  ThreadID:DWord;
begin
for i:=0 to 4 do
begin
messagebox(application.Handle,'123','提示信息',mb_ok);
if (i=2) then
begin
hthread:=CreateThread(nil,0,@MyThreadfunc,nil,0,ThreadID);//利用这种线程怎么说呢,肯定方便啦,但是
//肯定功能上受到好多限制,所以啊,自己写,下次贴个上来
end;
end;
end;
///
function TestCallBack( Func:PFCALLBACK ):integer;
begin
gCallBack:=Func;
testpro;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
//testpro;
TestCallBack(@CBFunc);
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
self.ListBox1.Clear;
end;
end.
使用回调函数需要注意的地方:
type PFCALLBACK = function(Param1:integer;Param2:integer):integer;stdcall;
 // 定义回调函数的类型
 function CBFunc(Param1:integer;Param2:integer):integer;stdcall;
//全局函数定义,指向函数的函数,指针!!!名字可以随便取,但参数之类的需要与定义
//的函数类型一致。
 function CBFunc(Param1:integer;Param2:integer):integer;
//写该函数体就没什么好说拉
function TestCallBack( Func:PFCALLBACK ):integer;
//传递回调函数的入口地址,最重要啦!

 

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/whbfeng/archive/2006/06/30/856051.aspx