Mega Code Archive

 
Categories / Delphi / Examples
 

Did you ever need to run a routine by name

Title: Did you ever need to run a routine by name? Question: Well, you can do it. Sort of... using Delphi's TMethod you can run a routine by name. Answer: To do that you just need to do the following... type TForm1 = class(TForm) Button1: TButton; procedure Button1Click(Sender: TObject); procedure Hello_World(Sender: TObject); // Your routines (that you'll run by name) must be here private { Private declarations } procedure ExecuteRoutine(Instance: TObject; Name: string); public { Public declarations } end; var Form1: TForm1; type TExecute = procedure of object; // The most important routine procedure TForm1.ExecuteRoutine(Instance: TObject; Name: string); var Routine: TMethod; Execute: TExecute; begin Routine.Data := Pointer(Instance); Routine.Code := Instance.MethodAddress(Name); // Returns the address of a published method. (* MethodAddress is used internally by the streaming system. When an event property is read from a stream, MethodAddress converts a method name, specified by Name, to a pointer containing the method address. There should be no need to call MethodAddress directly. If Name does not specify a published method for the object, MethodAddress returns nil. *) if Routine.Code = nil then Exit; Execute := TExecute(Routine); Execute; end; procedure TForm1.Button1Click(Sender: TObject); begin ExecuteRoutine(Form1, 'Hello_World'); end; procedure TForm1.Hello_World(Sender: TObject); begin ShowMessage('This is a test'); end;