1. Home
  2. Computing & Technology
  3. Delphi Programming

How to execute a method (procedure/function) by name

By Zarko Gajic, About.com

Here's a simple trick to execute a Delphi object's method by name:

~~~~~~~~~~~~~~~~~~~~~~~~~
type
   TForm1 = class(TForm)
     Button1: TButton;
     procedure Button1Click(Sender: TObject) ;
     procedure CallMeByName(Sender: TObject) ;
   private
     procedure ExecMethod(OnObject: TObject; MethodName: string) ;
   end;

var
   Form1: TForm1;

type
   TExec = procedure of object;

procedure TForm1.ExecMethod(OnObject: TObject; MethodName: string) ;
var
   Routine: TMethod;
   Exec: TExec;
begin
   Routine.Data := Pointer(OnObject) ;
   Routine.Code := OnObject.MethodAddress(MethodName) ;
   if NOT Assigned(Routine.Code) then Exit;
   Exec := TExec(Routine) ;
   Exec;
end;

procedure TForm1.CallMeByName(Sender: TObject) ;
begin
   ShowMessage('Hello Delphi!') ;
end;

procedure TForm1.Button1Click(Sender: TObject) ;
begin
   ExecMethod(Form1, 'CallMeByName') ;
end;


~~~~~~~~~~~~~~~~~~~~~~~~~

Delphi tips navigator:
» Activate a control hint from code
« How to delete an item from a dynamic (string) array

Zarko Gajic
Guide since 1998

Zarko Gajic
Delphi Programming Guide

Explore Delphi Programming
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. Delphi Programming
  4. Coding Delphi Applications
  5. Delphi Tips and Tricks
  6. 2004 Delphi Tips
  7. How to execute a method (procedure/function) by name

©2009 About.com, a part of The New York Times Company.

All rights reserved.