Reputation:
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.
Upvotes: 1
Views: 9796
Reputation: 1
Module Module1
Public Function InstanceNewForm(ByRef ParentForm As Form, ByRef Childform As Form) As Boolean
Dim bOpen As Boolean = False
Dim frm As Form
For Each frm In ParentForm.MdiChildren
If Childform.Name = frm.Name Then
Childform.Focus()
bOpen = True
Exit For
End If
Next
If Not bOpen Then
With Childform
.StartPosition = FormStartPosition.CenterScreen
.MdiParent = Parentform
.Show()
End With
End If
frm = Nothing
Return bOpen
End Function
End Module
The above code will check to see if a mdi form is already loaded in the parent container and if its already active will set the focus to it. Otherwise it will create the mdi form.
Just call it from anywhere the mdi form needs to be loaded. ex: call InstanceNewForm(me,form2)
Works like a charm everytime!!
Upvotes: 0
Reputation: 24142
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?
Upvotes: 2
Reputation: 17964
private Form frm;
public void ToggleForm() {
if(frm == null) {
frm = new Form();
frm.Show();
}
else {
frm.Close();
frm = null;
}
}
Upvotes: 2
Reputation: 55049
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.
Upvotes: 1
Reputation: 4608
You need to keep a reference to ibx
. Your code creates a new inbox
everytime it's run.
Upvotes: 0