6

is it possible to create and show TForm without having source files for it ? I want to create my forms at runtime and having the empty *.dfm and *.pas files seems to me useless.

Thank you

Martin Reiner
  • 2,167
  • 2
  • 20
  • 34

2 Answers2

10

Do you mean like this?

procedure TForm1.Button1Click(Sender: TObject);
var
  Form: TForm;
  Lbl: TLabel;
  Btn: TButton;
begin

  Form := TForm.Create(nil);
  try
    Form.BorderStyle := bsDialog;
    Form.Caption := 'My Dynamic Form!';
    Form.Position := poScreenCenter;
    Form.ClientWidth := 400;
    Form.ClientHeight := 200;
    Lbl := TLabel.Create(Form);
    Lbl.Parent := Form;
    Lbl.Caption := 'Hello World!';
    Lbl.Top := 10;
    Lbl.Left := 10;
    Lbl.Font.Size := 24;
    Btn := TButton.Create(Form);
    Btn.Parent := Form;
    Btn.Caption := 'Close';
    Btn.ModalResult := mrClose;
    Btn.Left := Form.ClientWidth - Btn.Width - 16;
    Btn.Top := Form.ClientHeight - Btn.Height - 16;
    Form.ShowModal;
  finally
    Form.Free;
  end;

end;
Andreas Rejbrand
  • 105,602
  • 8
  • 282
  • 384
  • 1
    Ah, I thought that for dynamic creating of the forms I need those files, I wouldn't believe it's so easy (next time I will try before ask). Thank you – Martin Reiner Dec 21 '11 at 19:55
  • 4
    @Martin the .dfm file parsing converts the .dfm file into property assignments just like the code in Andreas's excellent answer. – David Heffernan Dec 21 '11 at 19:57
  • 2
    +1 Good answer. On a side note, you do not have to use variables for each control added to the form. You could, for example, use `with TLabel.Create(Form) do` to add a label and modify its properties. Delphi will assign it a unique name and you can change it if you wish. – Jerry Gagnon Dec 21 '11 at 20:23
  • 3
    @Jerry: I usually give the controls explicit variables, because I tend to need those. For instance, I might want to do `Btn2.Left := Btn1.Left + Btn1.Width + 16`. – Andreas Rejbrand Dec 21 '11 at 20:32
  • 3
    @MartinReiner Just be aware that quite a number of components are less than easy to work with when instantiated at run-time they rely on the Loaded method being called. That normally only happens through the streaming mechanism, ie with components put on a form at design time. And this is something I have not just seen with "obscure" little known components. Many component developers fall victim to the assumption that everything is done at design-time. – Marjan Venema Dec 21 '11 at 21:30
  • @Marjan; Just such a glitch with Loaded hit me today. – Warren P Dec 21 '11 at 23:08
3

Yes, it is possible:

procedure TForm1.Button1Click(Sender: TObject);
var
  Form: TForm;

begin
  Form:= TForm.Create(Self);
  try
    Form.ShowModal;
  finally
    Form.Free;
  end;
end;
kludg
  • 27,213
  • 5
  • 67
  • 118