How to create form dynamically in Delphi

0

I'm having trouble creating form in Delphi, I'm using a procedure but it's giving a direct error.

Can anyone tell me a more efficient way to create a form in Delphi?

Current code:

procedure TLogin.CriarForm(NomeForm: TFormClass);
begin
  //Procedimento para criar formulario na memória
  with NomeForm do begin
    Try begin 
      TForm(NomeForm):=NomeForm.Create(Application); 
      TForm(NomeForm).Showmodal;
    end;

    Finally
      FreeAndNil(NomeForm);
    End; 
  end;
end;
    
asked by anonymous 13.09.2016 / 20:56

2 answers

1

The error in your code is in:

procedure TLogin.CriarForm(NomeForm: TFormClass);
begin
  //Procedimento para criar formulario na memória
  with NomeForm do begin
    Try begin //<- Não se abre um bloco begin-end dentro de blocos try-finally
      TForm(NomeForm):=NomeForm.Create(Application); 
      TForm(NomeForm).Showmodal;
    end; 

    Finally
      FreeAndNil(NomeForm);
    End; 
  end;
end;

The correct form would be:

procedure TLogin.CriarForm(NomeForm: TFormClass);
begin
  //Procedimento para criar formulario na memória
  with NomeForm do 
  begin
    Try
      TForm(NomeForm):=NomeForm.Create(Application); 
      TForm(NomeForm).Showmodal;
    Finally
      FreeAndNil(NomeForm);
    End; 
  end;
end;
    
15.09.2016 / 19:51
0

If "TFormClass" is a class reference, the code looks like this:

procedure TLogin.CriarForm(NomeForm: TFormClass);
var
  form: TForm;
begin
  form := NomeForm.Create(Application);
  try
    form.ShowModal; 
  finally
    form.Free;
  end;
end;

In this case, NameForm would be a reference to the TForm or descending class to be created. P.ex .: type TFormClass = class of TForm; ...

CreateForm (TForm1); // creates and displays an instance of TForm1   CreateForm (TForm2); // creates and displays an instance of TForm2   ...

    
07.07.2017 / 16:30