Problem with Delphi OnClick with multiple modules

When I make a dynamic component from a block, I have no problem creating an OnClick event. When I make a dynamic component from block 2 , I cannot access the OnClick event.

unit Unit1  
type  
    TForm1 = class(TForm)  
      procedure FormCreate(Sender: TObject);  
    private  
      { Private declarations }  
    public  
      Procedure ClickBtn1(Sender: TObject);  
    end;  

var  
    Form1: TForm1;  
    MyBtn1: TButton;  
implementation  

{$R *.dfm}

{ TForm1 }
uses Unit2;

procedure TForm1.ClickBtn1;  
begin  
    MyBtn1.Caption := 'OK';  
    MakeBtn2;  
end;


procedure TForm1.FormCreate(Sender: TObject);  
begin  
    MyBtn1 := TButton.Create(Self);  
    MyBtn1.Parent := Form1;  
    MyBtn1.Name := 'Btn1';  
    MyBtn1.Left := 50;  
    MyBtn1.Top := 100;  
    MyBtn1.Caption := 'Click Me';  
    MyBtn1.OnClick := ClickBtn1;  
end;  


end.



unit Unit2;

interface

uses
    Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
    Dialogs, StdCtrls;

procedure MakeBtn2;  
procedure ClickBtn2;      
var  
    MyBtn2: TButton;  

implementation

Uses Unit1;

procedure MakeBtn2;  
begin  
    MyBtn2 := TButton.Create(Form1);  
    MyBtn2.Parent := Form1;  
    MyBtn2.Name := 'Btn2';  
    MyBtn2.Left := 250;  
    MyBtn2.Top := 100;  
    MyBtn2.Caption := 'Click Me';  
    MyBtn2.OnClick := ClickBtn2;    //Compiler ERROR
end;  

procedure ClickBtn2;  
begin  
    MyBtn1.Caption := 'OK';  
end;  
end.  
+3
source share
2 answers

Take a look at this article “ Creating a component at runtime

Quote:

, . click, ? , IDE , , .

, . :

{This method is from another button that when pressed will create
 the new button.}
procedure TForm1.Button1Click(Sender: TObject);
var
  btnRunTime : TButton;
begin
  btnRunTime := TButton.Create(form1);
  with btnRunTime do begin
    Visible := true;
    Top := 64;
    Left := 200;
    Width := 75;
    Caption := 'Press Me';
    Name := 'MyNewButton';
    Parent := Form1;
    OnClick := ClickMe;
  end;
end;

{This is the method that gets assigned to the new button OnClick method}
procedure TForm1.ClickMe(Sender : TObject);
begin
  with (Sender as TButton) do
    ShowMessage('You clicked me');
end;

, ClickMe, Form1:

type
  TForm1 = class(TForm
  ...
  ...
  private
    procedure ClickMe(Sender : TObject);
  published
  end;

. :

+2

, ? .

OnClick TNotifyEvent,

procedure(Sender: TObject) of object;

, (, ), , TObject. MakeBtn2 , Sender: TObject.

+1

Source: https://habr.com/ru/post/1725536/


All Articles