I presume that you have a main form, which creates a non-modal child form. Since this child form can be closed independently from the main one, you can have two scenarios:
- Child form hasn't been created yet, or it was closed. In this case, create the form and show it.
- Child form is already running. In this case, you only need to show it (it may be minimized, and you will want to restore it).
Basically, your main form should keep track of the child form's lifetime, by handling its FormClosed
event:
class MainForm : Form
{
private ChildForm _childForm;
private void CreateOrShow()
{
// if the form is not closed, show it
if (_childForm == null)
{
_childForm = new ChildForm();
// attach the handler
_childForm.FormClosed += ChildFormClosed;
}
// show it
_childForm.Show();
}
// when the form closes, detach the handler and clear the field
void ChildFormClosed(object sender, FormClosedEventArgs args)
{
// detach the handler
_childForm.FormClosed -= ChildFormClosed;
// let GC collect it (and this way we can tell if it's closed)
_childForm = null;
}
}