Is it possible to dynamically create form without having *.dfm and *.pas files?
Asked Answered
S

2

7

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

Surgy answered 21/12, 2011 at 19:43 Comment(0)
C
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;
Culverin answered 21/12, 2011 at 19:49 Comment(6)
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 youSurgy
@Martin the .dfm file parsing converts the .dfm file into property assignments just like the code in Andreas's excellent answer.Logicize
+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.Zeringue
@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.Culverin
@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.Institution
@Marjan; Just such a glitch with Loaded hit me today.Wedding
T
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;
Tijuanatike answered 21/12, 2011 at 19:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.