Click here to Skip to main content
15,867,488 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
How can I go about closing a Child form if it's already open? And if it isn't already open, then open it?
Posted

First of all, there is not such relationship as child-parent forms.
[EDIT: There are MDIParent and MDIChildren, but this is not exactly the same thing. Also, I don't think we discuss MDI. Thanks to CS2011 who pointed out that relationship between forms in case of MDI.]

There are Owned Forms and Owner Forms. You really need to use this relationship; it affect activation behavior (all forms of the same application will open activate together). You need to use System.Windows.Forms.Form.Owner. It's good to make all forms owned by the main form and set Form.ShowInTaskbar to false for all owned form, by the apparent reason.

Now, of you need to open, close and reopen non-main (as we hopefully agree, owned forms), you need to implement the following behavior: hide form instead of closing:

C#
protected override void OnFormClosing(FormClosingEventArgs e) {
   if (e.CloseReason == CloseReason.UserClosing) {
       e.Cancel = true;
       Hide();
   } //if
} //OnFormClosing


Pay attention for check up of CloseReason: the behavior will be applied only to attempt to close the form by the user.

The show can be lazy, but regardless to the show state of the form does not matter, if can be currently shown or not:
C#
MyForm MyForm;

//...

if (MyForm == null) {
   MyForm = new MyForm();
   this.AddOwnedForm(MyForm); //if "this" is a main form
   MyForm.ShowInTaskbar = false;
} //if
MyForm.Show(); //unconditional: if already shown, it's fine.


—SA
 
Share this answer
 
v3
Comments
CS2011 20-May-11 23:15pm    
My 5+ for this answer.
Sergey Alexandrovich Kryukov 20-May-11 23:35pm    
Thank you very much.
--SA
Sergey Alexandrovich Kryukov 21-May-11 0:17am    
Added a note about MDI. Thank you for helping me to add this fix.
--SA
Abhinav S 21-May-11 0:33am    
My 5 for this detailed answer.
Sergey Alexandrovich Kryukov 21-May-11 15:55pm    
Thank you, Abhinav.
--SA
Form a parent form you have to create an instance to be able to show the child form. You can use that instance to see the state of the child form.
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 20-May-11 22:41pm    
There is no such thing as "child form" or "parent form". And you did not answer. Sorry, 1.
--SA
Sergey Alexandrovich Kryukov 20-May-11 22:59pm    
Please see my solution.
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900