views:

49

answers:

4

Hi All

How can I go about closing a Child form if it's already open? And if it isn't already open, then open it?

Thank you

I already have this code, which doesn't work, obviously:

Form ibx = new inbox();
if(ibx.Visible)
ibx.Dispose();
else
ibx.Show();

All that the above does is creates a new form whether or not it's already open.

+3  A: 
private Form frm;
public void ToggleForm() {
  if(frm == null) {
    frm = new Form();
    frm.Show();
  }
  else {
    frm.Close();
    frm = null;
  }
}
Carra
+1  A: 

You need to keep a reference to ibx. Your code creates a new inbox everytime it's run.

Robert Massa
+2  A: 

In your main form, when you create the first childform, keep a reference to it. Currently you're creating a new childform every time you run that code and then you check if the newly created form is visible.

Also be aware that your subject talk about opening and closing but your code seems to just be dealing with hiding and showing.

Carra's code is a good sample how to do it, but be careful if the childform can be closed from anywhere else.

ho1
+1  A: 

If what you want to achieve is opening a form only if it isn't already open, then bring it on front when it is, then the following code might help.

private void tsmiMenuOption_Click(object sender, EventArgs e) {
    // Assuming this method is part of an MDI form.
    foreach(Form child in this.MdiChildren)
        if (child.Name == MyForm.Name) {
            child.BringToFront();
            return;
        }

    MyForm f = new MyForm();
    f.MdiParent = this;
    f.Show();
}

So, this is untested pseudo-c#-code that verifies if MyForm is already opened and contained in the MdiContainer.Children. If it is, then it brings this form (MyForm) to the front. If it is not, then it simply instantiate and opens it.

Is this about what you want?

Will Marcouiller
The logic behind your answer is correct, spot on, however I'm not using MDI but this answer will definitely come in handy when I do in a few days for a separate project. Thanks very much :) +1
lucifer
Thanks for mentionning my answer will help you! There might be some other clever way to do it using Linq or so. =)
Will Marcouiller