Kiril Hadjiev
Kiril Hadjiev

Reputation: 302

get method as text

I need to save and load some properties to a database and I am stuck with this. I have a form with several methods and a button. button.onclick event is assigned to one of the form's methods. I need to get the name of the assigned method as string (just like Object inspector "form1.proc1") and save it to the database. Later I need to get the method name from the database and assign button.onclick to the corresponding form's method. Is this possible at all?

Form1 = class(TForm)
...
procedure proc1(Sender: TObject);
procedure proc2(Sender: TObject);
procedure proc3(Sender: TObject);

Button1.OnClick = readMethodNameFromDatabase; 
...
saveMethodToDatabase(Button1.OnClick);

Upvotes: 1

Views: 1875

Answers (1)

David Heffernan
David Heffernan

Reputation: 612894

You can obtain a method, given its name, like this:

function TForm1.MethodFromName(const Name: string): TNotifyEvent;
begin
  TMethod(Result).Data := Self;
  TMethod(Result).Code := MethodAddress(Name);
  if TMethod(Result).Code=nil then
    raise Exception.CreateFmt('Count not find method named %s', [Name]);
end;

This is the mechanism that the RTL uses when reading your .dfm files. It relies on the method being published.

You can call it like this:

Button1.OnClick := TNotifyEvent(MethodFromName('Button1Click'));

Naturally you'd substitute a database read in the final code.


As for the second part of your question, you can get the name of an event handler with this code:

MethodName(@Button1.OnClick);

Upvotes: 4

Related Questions