Search code examples
delphidelphi-10-seattle

FormCreate procedure


I have two units in my project as follow:

1 - Connexion unit:

unit Connexion;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;

type
  TFConn = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Déclarations privées }
  public
    { Déclarations publiques }
  end;

var
  FConn: TFConn;

implementation

{$R *.dfm}

uses MainForm;

procedure TFConn.Button1Click(Sender: TObject);
begin
  if not Assigned(FMain) then
    begin
      FMain := TFMain.CreateNew(Application);
      FMain.OnClose := FMain.FormClose;
      FMain.ShowModal;
    end;
end;

end.

2 - MainForm unit :

unit MainForm;

interface
   uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;

type
  TFMain = class(TForm)
     Constructor  FormCreate(Sender: TObject);overload;
     procedure FormClose(Sender: TObject; var Action: TCloseAction);
  end;
Var
  FMain : TFMain;
implementation

Constructor  TFMain.FormCreate(Sender: TObject);
var B :  TButton;
begin
   inherited;
   B := TButton.Create(Self);
   B.Parent := Self;
   B.Caption := 'Button2';
end;

procedure tfmain.FormClose(Sender: TObject; var Action: TCloseAction);
begin
  FMain := Nil;
end;
end.

The problem is that the procedure FormCreate in MainForm unit not working , I know that I miss something in the declaration , because the procedure should fire while the creation of the FMain form .

The application run without any error , but it should create B button on the FMain form.

How can I do that?


Solution

  • Constructor  FormCreate(Sender: TObject);overload;
    

    is wrong. It should be:

    procedure FormCreate(Sender: TObject);
    

    The other problem is that you must set the OnCreate event to refer to FormCreate. Do this in the events page of the object inspector.

    That will also need you to have a dfm file for this form which you appear not to have. Once you restore the dfm file you can set the OnClose event handler in the same way. You'd need to switch to Create rather than CreateNew.

    You can't set the OnCreate event handler in code because the form has already been created.

    If there is a good reason not to have a dfm file and do everything in code then you could need to add a constructor. Do that by overriding the virtual constructor:

    constructor Create(AOwner: TComponent); override;
    

    Finally, very much of the code in the question looks dubious, shall I saw. Strange use of global variables. Odd naming. Setting important events like OnClose from outside the class. Testing against nil that suggests weak design. I think there are problems ahead.