Mega Code Archive

 
Categories / Delphi / String
 

How to set a Component Event by a string

Title: How to set a Component Event by a string Question: sometime we want to set a object event by a string that is a name of the event handler. The article show the technique how to do this. Answer: Assume you have two event handler for a button of a form. This Article show the technique how to assign the button event with a string of a event handler. It is important to assgin the event handler to be a published method. So If there are two published event handler called 'ClickForShowMsg' and 'ClickForShowdlg' respectively procedure TForm1.ClickForShowMsg(Sender: TObject); begin ... end; procedure TForm1.ClickForShowDlg(Sender: TObject); begin ... end; // we can set the event of Component by a name of the handler procedure TForm1.Button2Click(Sender: TObject); var mAddr : Pointer; Method: TMethod; begin mAddr := Self.MethodAddress(Edit1.Text); // Edit1.Text is the name of handler if Assigned(mAddr) then begin Method.Code := mAddr; Method.Data := Self; SetMethodProp(Button1, 'OnClick', Method); end; end;