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;
//傳遞迴調函數的入口地址,最重要啦!