The cleanest way to achieve what you want is for you to control the destruction of the forms.
The only form that needs to be owned by Application
is your main form. That needs to be so because the first form created by a call to Application.CreateForm
is designated to be the main form. So, my advice is that you should make one call, and one call only to Application.CreateForm
, to create the main form. For all your other forms, create them by calling their constructors. Let the other forms be owned by the main form. When it's time to shut down, destroy the main form, and let it take all the owned forms with it.
You might write your .dpr code like so:
begin
LoadDlls;
try
Config := TConfig.Create;
try
Application.Initialize;
Application.Title := 'Foo';
Application.CreateForm(TMainForm, MainForm);
try
OtherForm := TOtherForm.Create(MainForm);
YetAnotherForm := TYetAnotherForm.Create(MainForm);
Application.Run;
finally
FreeAndNil(MainForm);
// will destroy the other forms since they are owned by the main form
end;
finally
Config.Free;
end;
finally
UnloadDlls;
end;
end;
One other point to make is that perhaps you don't need to unload the DLLs. Since this is clearly an executable, the system will unload them anyway. Why do you need to do so?