Gem
Gem

Reputation: 526

Call Button1Click in Form1/Unit1 from Unit2

I've downloaded Delphi XE7 and having some problems with accessing another Units... I need to call procedures from another units, so I'll give a very basic illustration, simple program... This is code from main Unit1 with form and button1:

unit Unit1;
interface
uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics,
  Controls, Forms, Dialogs, StdCtrls, Unit2;
type
  TForm1 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation
{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
begin
ShowMessage('Hello');
end;

end.

And this is the code from Unit2:

unit Unit2;
interface
implementation
uses Unit1;
end.

Now, how is it possible to make procedure Button1Click like in Unit2 to showmessage let's say HelloFromUnit2 when button1 on form1 is clicked? Unit2 is codeUnit without anything..

Upvotes: 1

Views: 1949

Answers (3)

Tom Brunberg
Tom Brunberg

Reputation: 21045

The header of your post doesn't match the question in the text

"Call Button1Click in Form1/Unit1 from Unit2" vs. "Now, how is it possible to make procedure Button1Click like in Unit2 to showmessage let's say HelloFromUnit2 when button1 on form1 is clicked?"

I answer the question in the text (as I understand it). If this is not what you intended, you might want to rephrase the question in the text.

Add, to Form1.Button1Click, a call to a new procedure in unit2

procedure TForm1.Button1Click(Sender: TObject);
begin
  ShowMessage('Hello');
  SayHelloFromUnit2;  // <---- add this
end;

In unit2 add the following to the interface section:

procedure SayHelloFromUnit2;

and to the implementation section

uses Vcl.Dialogs;

procedure SayHelloFromUnit2;
begin
  ShowMessage('Hello from unit2');
end;

Upvotes: 1

Jens Borrisholt
Jens Borrisholt

Reputation: 6402

Use the build in procedure for calling the Click handler

Leave form 1 the way it is:

unit Unit2;

interface

implementation

uses 
  Unit1;

procedure Click;
begin
  if Assigned(Form1) then
    Form1.Button1.Click;
end;

end.

Upvotes: 2

No&#39;am Newman
No&#39;am Newman

Reputation: 6477

Add a procedure declaration to the public section of TForm1, like this

type
 TForm1 = class(TForm)
           Button1: TButton;
           procedure Button1Click(Sender: TObject);
          private
          public
           Procedure SayHello;   
          end;
...
procedure TForm1.SayHello;
begin
 ShowMessage('Hello');
end;

end.

Then in Unit2 you would call this procedure. You would have to ensure that Form2 has already been instantiated - or create a new instance for your call.

Do not use this mechanism for event handlers!

Upvotes: 1

Related Questions