At startup of a Windows Forms application I read a XML file. If this file doesn't exist or doesn't have a certain setting I want to display a MessageBox to the user indicating the problem and then close the application.
I tried to do that in the Load
event of the main form with Application.Exit()
like so:
private void MainForm_Load(object sender, EventArgs e)
{
if (!StartupSettingsCorrect())
{
MessageBox.Show("Blabla... Can't start application.");
Application.Exit();
}
// Other stuff...
}
But this doesn't seem to be clean. (The application is running but "invisible" with no form on the screen.)
What is instead the best way and place for a clean shutdown in this situation?
Thank you for help in advance!
Environment.Exit()
should do the trick. At least it worked for me in the situation you described.
According to MSDN, this method
Terminates this process and gives the underlying operating system the specified exit code.
Read the XML file in the Main method of the Program.cs file (should be autogenerated for you). If you get an error then don't load the form.
static void Main ()
{
if ( !StartupSettingsCorrect())
{
MessageBox.Show( "Blabla... Can't start application." );
}
else
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault( false );
Application.Run( new MainForm() );
}
}
This technique avoids starting up the main form in the first place, if some pre-requisites haven't been met.
You're application won't be unloaded until you come out of the MessageBox though.
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
if (!StartupSettingsCorrect())
{
MessageBox.Show("Blabla... Can't start application.");
}
else
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
The Application.Exit method stops all running message loops on all threads and closes all application windows. But depending on when it's called, it doesn't necessarily force the process to end. If you call Application.Exit before loading your main form, that should work.
Another solution would be to close your main form - the rest will then be handled for you. This is the equivalent to using Application.Shutdown.
Otherwise you can use Environment.Exit. I believe this terminates the process without unwinding the stack and without executing finally blocks. So it's very rude, but this may not be an issue in your current context.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With