Correct way to destroy a form and show another in Delphi

James picture James · Feb 13, 2012 · Viewed 9.8k times · Source

Currently in my program I have a Startup form, and a Main form. The startup form shows for a second or two.

Right now, I have the following code within a timer:

  frmStartup.Destroy;

  frmMain := TfrmMain.Create(Self);
  frmMain.Show;

Right now, I'm not sure if this is the correct way to do it.. It works, but when calling application.Terminate(); I receive an access violation message, leading my to believe that I have done something wrong in the destruction of the startup form..

If anyone could show the the correct procedure for doing what I want (non-modally) It would be greatly appreciated.

Thanks in advance,

EDIT:

Thanks for all the feedback, I fixed my access violations by simply adding the code:

  Action := caFree;

Into the frmStartup.formClose method.

Answer

Ken White picture Ken White · Feb 13, 2012

Don't create the frmStartup using Application.CreateForm. The first form created there becomes your application's main form, and if that's frmStartup you're destroying it outside Application knowledge.

Instead, use a normal Form.Create in your project source (.dpr) file:

var
  frmStartup: TfrmStartup;

begin
  Application.Initialize;
  Application.MainFormOnTaskBar := True;
  frmStartup := TfrmStartup.Create(nil);  // No owner assigned here!
  frmStartup.Show;
  frmStartup.Update;

  Application.CreateForm(TfrmMain, frmMain); // Let Application have this for main form
  // Delay here if needed
  frmfrmStartup.Free;
  Application.Run;
end.