Archive for September, 2010

Close Form programmatically in c# in the constructor

Sometimes you instanciate a Form and you want to do some validations in the constructor. If the validation fails, you want to close the form. Calling Application.Exit() directly in the constructor won’t work.

You need to call the Application.Exit in the OnLoad method.

If you don’t want to see the form at all during the validation process, put the window invisible on startup so it won’t be showed.

Set the WindowState to minimized and ShowInTaskbar to false in the Designer.
If the validation succeeded, set the WindowState to normal or maximized and ShowInTaskbar to true.

Categories: C#, WindowsForm