First of all, even though a form can be closed, there is not such thing as "Open" operation (and, hence, it is not possible to know if a form is "already opened" :-). An instance of a Form is instantiated via its constructor, then shown, then closed.
Everything depends on how you close the form. I think the best way of closing is hiding the form; to do this, override :
protected override void OnFormClosing(FormClosingEventArgs e) {
if (e.CloseReason == CloseReason.UserClosing) {
e.Cancel = true;
Hide();
} else
base.OnFormClosing(e);
}
You can get the same effect by handling the event
FormClosing
, but override is implemented easier.
For more detail on what happens on closing the form, please see
http://msdn.microsoft.com/en-us/library/system.windows.forms.form.close.aspx[
^]. As you can see, hiding the form is the recommended way of handling this situation. Note, that a closed form is disposed (see below).
In this way, only one operation is needed:
Form.Show
.
If you need the form to be really closed, you can test the predicate
Form.IsDisposed
. To show the form again, you will need to instantiate an instance of the form again and then show new instance, as a disposed cannot be shown. Another way is checking
Application.OpenForms
and trying to find a form in question in the collection.
I do not recommend closing of the form by the user; hiding is much better. When a form is hidden, it preserved its status and status of all the controls, when a form is shown again. Don't think you save memory on closing the form. You don't.
Don't forget the ownership relationship between forms. It is better to make non-main forms owned by main forms:
Form MyOwnedForm = new CustomerInformationForm();
MyOwnedForm.Owner = MyMainForm;
MyOwnedForm.ShowInTaskbar = false;
MyOwnedForm.Show(MyMainForm);
This will guarantee coherent activation of the forms of the same application, should be used with
ShowInTaskbar = false
for consistency.
A final recommendation: it's the best to keep number of forms per application to bare minimum, with one more complex form being the best option. Use tabbed UI, docking UI or something like that.
—SA