I am trying to learn callbacks in Delphi (7). Could not find a complete simple tutorial, so I puzzled together a few bits here and there. This is my first attempt, of course trivial.
My form contains a button and a label. For the test, I make a loop in the onClick code, and every time do a callback function.
The code is below. It works, but I am in doubt if it's "correct" to have application.processmessages where I have it. And, if I define / apply the callback functionality correctly.
// ----------- demo to test Callbacks
// https://stackoverflow.com/questions/11314641/method-pointer-and-regular-procedure-incompatible
//
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TCallBackFunction = procedure(sig: integer) of object;
TForm1 = class(TForm)
lblProgress: TLabel;
btn1: TButton;
procedure btn1Click(Sender: TObject);
private
{ Private declarations }
procedure tcb (sig: integer);
public
{ Public declarations }
procedure dowithcallback(const something: integer; thefunction: TCallBackFunction);
end;
var
Form1: TForm1;
testvar : integer;
implementation
{$R *.dfm}
// test procedure used for callback argument
//
procedure TForm1.tcb(sig: integer);
begin
testvar := sig;
lblProgress.Caption := inttostr(testvar);
application.ProcessMessages ;
end;
// The procedure that defines the callback function
//
procedure TForm1.dowithcallback(
const something: integer;
thefunction: TCallBackFunction);
begin
if assigned(thefunction) then
begin
thefunction(something)
end;
end;
//
// button click
//
procedure TForm1.btn1Click(Sender: TObject);
var
i : integer;
begin
testvar := 0;
for i := 1 to 10 do
begin
dowithcallback(i, tcb);
sleep(500);
end;
end;
end.
Any feedback welcomed!