How to access TPanel child form controls?

1.9k views Asked by At

I have a main form with TPanel. I have also a Form2 with a TButton which I show in TPanel as a child. I mean TPanel of main form is parent of Form2. I use these steps to create the form2 in MainForm OnCreate method

MainFormOnCreate()

Form2 := TForm2.create(nil)
Form2.Parent := Panel1;
Form2.show;

But the problem is that when I access the button on Form2 it does nothing. For example, when I want to disable the button on Form2 I use this method

A button2 on main form with on click event

btn2OnClick();
Form2.btn.enabled := false;

But it does nothing. Some friends says it's because of child to TPanel it will get no message.

So give me a solution. Thanks in advance

2

There are 2 answers

1
Sir Rufo On

The main problem is, that you create 2 instances of TForm2.

Your .dpr file look like this

begin
  Application.Initialize;
  Application.CreateForm( TForm1, Form1 );
  Application.CreateForm( TForm2, Form2 );
  Application.Run;
end.

After you create an instance of TForm2 in TForm1.OnCreate and save this instance into global variable Form2, another instance of TForm2 is created and stored into Form2.

In the TForm1.btn5.OnClick event you address the second created, non visible TForm2.


Solution

  • go to Project / Options -> Formula and remove TForm2 from AutoCreate List
  • store the instance of TForm2 created inside of TForm1 in a private class field of TForm1

Your code should look like this

.dpr file:

begin
  Application.Initialize;
  Application.CreateForm( TForm1, Form1 );
  Application.Run;
end.

Unit1.pas

TForm1 = class( TForm )
...
procedure FormCreate( Sender : TObject );
procedure btn2Click( Sender : TObject );
private
  FForm2 : TForm2;
  ...
end;

procedure TForm1.FormCreate( Sender : TObject );
begin
  FForm2 := TForm2.Create( Self );
  FForm2.Parent := Panel1;
  FForm2.Show;
end;

procedure TForm1.btn2Click( Sender : TObject );
begin
  FForm2.btn.Enabled := True;
end;
0
user1969258 On

Try this one

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

type
  TForm1 = class(TForm)
    Panel1: TPanel;
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
    procedure FormCreate(Sender: TObject);
  private
    lForm: TForm;
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
begin
  if Assigned(lForm) then
    TForm2(lForm).Button1.Enabled:= False;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  lForm := TForm2.Create(self);
  lForm.Parent := Panel1;
  lForm.Align:= alClient;
  lForm.show;
end;