I have an application with a MainForm which is a loading screen. This Form is displayed while some stuff are done in the background, such as deciding which form to launch next. I cannot get this to work, I keep having an access violation error.
I got why thanks to this subject : Open two forms at startup in c++ builder. But the proposed solution is not acceptable for me as I do not know at design time which form will be displayed first.
What is the correct way to do this?
I have an application with a MainForm which is a loading screen.
Don't do that. In VCL, the MainForm
can't be changed once it is set, and the app will exit when the MainForm
is closed. The MainForm
is set by the first call to Application->CreateForm()
. If you want to create Forms before the MainForm
is created, you must use the new
operator instead, eg:
Application->Initialize();
TLoadingForm *LoadingForm = new TLoadingForm(Application);
LoadingForm->Show();
LoadingForm->Update();
...
Application->CreateForm(__classid(TForm1), &Form1);
...
LoadingForm->Close();
delete LoadingForm;
Application->Run();
...
If you want to make decisions about which TForm
will be the real MainForm
at runtime, you can do that, eg:
Application->Initialize();
TLoadingForm *LoadingForm = new TLoadingForm(Application);
LoadingForm->Show();
LoadingForm->Update();
...
if (someCondition)
Application->CreateForm(__classid(TForm1), &Form1);
else
Application->CreateForm(__classid(TForm2), &Form2);
...
LoadingForm->Close();
delete LoadingForm;
Application->Run();
...
Be aware, though, that the IDE "owns" the main project source file, and it likely WILL modify/delete/corrupt your custom code at some point during your project's development lifetime. So be very careful with custom code you place between the calls to Application->Initialize()
and Application->Run()
. And make sure you have good backups.