Reputation: 1099
I want a procedure to be executed when an event is happened. But that procedure is set by another procedure(SetNotifierProc
).
Firstly I run this:
SetNotifierProc(Proc1);
And then Proc1
is executed whenever event triggered.
How could I code SetNotifierProc
to get a procedure as an argument and how to inform event handler to execute that procedure?
Problem: I have a TCPServerExecute
and want to run a procedure to show received data. But because I have multiple forms I want to set a procedure that handle received data.
Thanks
Upvotes: 3
Views: 1005
Reputation: 34889
If your procedure is an ordinary procedure without arguments:
Type
TForm1 = Class(TForm)
..
private
FMyProc : TProcedure;
public
procedure SetEventProc(aProc : TProcedure);
procedure TheEvent( Sender : TObject);
end;
procedure Test;
begin
// Do something
end;
procedure TForm1.SetEventProc(aProc: TProcedure);
begin
Self.FMyProc := aProc;
end;
procedure TForm1.TheEvent(Sender: TObject);
begin
if Assigned(FMyProc) then
FMyProc;
end;
// to set the callback to procedure "Test"
Form1.SetEventProc(Test);
If your procedure has arguments, declare a procedure type:
Type
MyProcedure = procedure( aString : String);
And if your procedure is a method :
Type
MyMethod = procedure( aString : String) of Object;
See also documentation about Procedural types
.
Upvotes: 3
Reputation: 2350
This should do the trick :-
Type
TTCPNotifyProc = Procedure(pData : String) Of Object;
TMyTCPServer = Class
Private
FNotifyProc : TTCPNotifyProc;
..
Public
Procedure SetNotifier(pProc : TTCPNotifyProc);
End;
Procedure TMyTCPServer.SetNotifier(pProc : TTCPNotifyProc);
Begin
FNotifyProc := pProc;
End;
Then whenever you need to call the procedure within your server class just call :-
If Assigned(FNotifyProc) Then
FNotifyProc(DataStringReceived);
Upvotes: 0