How to properly exit an application from the Main Form?

  • Thread starter Thread starter ESmith
  • Start date Start date
E

ESmith

When a user starts up my application, I want to check for some prerequisite
conditions, and if not met, the exit the application.

Example:

public Form1()
{
InitializeComponent();

if ( MandatoryConditionsNotPresent() )
{
MessageBox.Show ("So Sorry! Unable to run.");
Close() <-- if I do this, I'll get an exception thrown in
Application.Run(new Form1());
}
...
}


What is the proper way to exit gracefully? (Or do I just wrap the
Application.Run in a Try/Catch block?)

TIA!
 
I agree... Main() is the place to do it.

There have been times, however, when this was not an option for me. I cannot remember the reasons,
but I found if you need to close the window before it loads you can just add an event handler for
Paint during the loading of the form and then close it in the called function. This way the load
finishes, the paint event is fired, and the app can close without an error.

this.Paint += new PaintEventHandler(SharedServerSetup_Paint);
void SharedServerSetup_Paint(object sender, PaintEventArgs e)
{
this.Close();
}

---Tome
http://www.pcdotcom.com
 
One important reason for not doing this in the Form's constructor is
that if you ever inherit from it, Visual Studio will not be able to
design the child form.

You should check prerequisites for the application as a whole in the
Main() method.

If the form itself has prerequisites, and doesn't trust its calling
application, then they should be checked in the OnLoad() method,
because that's the first place at which you can test to see if the form
is being built by Visual Studio or by an application.
 
Back
Top