按我的理解,回调函数就是...钩子函数,当系统准备作某项工作时,就会自动调用。一般用在枚举系统资源等场合,如窗口、任务、字体等。
下面的例子用来枚举字体:function EnumFontsProc(var LogFont: TLogFont; var TextMetric: TTextMetric;
FontType: Integer; Data: Pointer): Integer; stdcall;
begin
with TStrings(Data) do
if ((Count = 0) or (Indexof(LogFont.lfFaceName) = -1)) then
if Pos('@', LogFont.lfFaceName) = 0 then
AddObject(LogFont.lfFaceName, TObject(FontType = TRUETYPE_FONTTYPE));
Result := 1;
end;procedure TFontComboBox.GetInstalledFonts;
var DC: HDC;
LFont: TLogFont;
begin
Items.Clear;
Zeromemory(@LFont, SizeOf(TLogFont));
LFont.lfCharset := DEFAULT_CHARSET;
DC := GetDC(0);
try
EnumFontFamiliesEx(DC, LFont, @EnumFontsProc, LongInt(Items), 0);
finally
ReleaseDC(0, DC);
end;
ItemIndex := 0;
end;这是我做的字体组合列表框代码的一部分,可用。
下面的例子用来枚举字体:function EnumFontsProc(var LogFont: TLogFont; var TextMetric: TTextMetric;
FontType: Integer; Data: Pointer): Integer; stdcall;
begin
with TStrings(Data) do
if ((Count = 0) or (Indexof(LogFont.lfFaceName) = -1)) then
if Pos('@', LogFont.lfFaceName) = 0 then
AddObject(LogFont.lfFaceName, TObject(FontType = TRUETYPE_FONTTYPE));
Result := 1;
end;procedure TFontComboBox.GetInstalledFonts;
var DC: HDC;
LFont: TLogFont;
begin
Items.Clear;
Zeromemory(@LFont, SizeOf(TLogFont));
LFont.lfCharset := DEFAULT_CHARSET;
DC := GetDC(0);
try
EnumFontFamiliesEx(DC, LFont, @EnumFontsProc, LongInt(Items), 0);
finally
ReleaseDC(0, DC);
end;
ItemIndex := 0;
end;这是我做的字体组合列表框代码的一部分,可用。
回调函数都是外部公共函数或类的静态成员函数,其函数内部所使用的变量也必须是公共变量或内的成员变量。
回调函数的另一个用途,是用于一些枚举函数,如EnumDisplayModes等,每找到一种支持的显示模式,就通知回调函数,由回调函数具体处理,这是因为EnumDisplayModes本身并不知道用户要如何处理.
使用回调函数可以提供这样一种机制:系统定义了一个框架,但不确定这个框架的具体功能,用户提供回调函数,定制系统的功能,这样,不同的用户提供不同的回调函数,可以使系统具有不同的功能.这就是所谓的plugin.
TCallBackFunction = function(s: string): integer;
CallMe(s: string): integer;procedure TestCallBack(CallBackFunction: TCallBackFunction); far; external 'Other';
{ Note that 'other' is a Dll containing the procedure TestCallBack }function CallMe(s: PChar): integer;
begin
{ what ever you need to do }
CallMe := 1; { What ever you need to return }
end;procedure TForm1.Button1Click(Sender: TObject);
begin
TestCallBack(CallMe);
end;type
TMainFunction = function(s: string): integer;
TestCallBack(MainFunc: TMainFunction);
{ in library Other implementation }
TestCallBack(MainFunc: TMainFunction);
var
result: integer;
begin
result:=MainFunc('test');
end;