views:

49

answers:

2

I have a mdicontainer form that summons forms. My problem is when the a user clicks again the menu for that form, it also make another instance of it.

What I did is declare a public class with a public variable on it ex: Boolean isFormOneOpen = false. Then every time formOne opens, it checks first the global variable I declared a while ago if it's false, if it is, instantiate an object of a formOne and then show it. Otherwise, do nothing. Very static, imagine if I have many forms, I have to declare a variable for each form to check if it's already open. Can you provide me a solution for this? Maybe a method that accepts a Form? Or any more clever way to do this.

A: 

Rather than a boolean, declare a variable of the form's type. Then just make sure the variable isn't Nothing and call it's .Open() method. This has the nice side effect of also bringing your existing form instance to the front if it's already open.

Even better, in VB.Net 2.0 and later all forms have a default instance with the same name as their type, so you can just say FormName.Open() and be done with it. However, I haven't tried this in an mdi situation before.

Joel Coehoorn
OK. Thanks, I'll try what you say.
yonan2236
+1  A: 

You don't need a variable, you could iterate the MdiChildren collection to see if the form is already opened. For example:

Private Sub btnViewChild_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnViewChild.Click
    For Each child In Me.MdiChildren
        If TypeOf child Is Form2 Then
            child.WindowState = FormWindowState.Normal
            child.Focus()
            Exit sub
        End If
    Next
    Dim frm As New Form2
    frm.MdiParent = Me
    frm.Show()
End Sub

The VB.NET-centric solution:

Private Sub btnViewChild_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnViewChild.Click
    Form2.MdiParent = Me
    Form2.WindowState = FormWindowState.Normal
    Form2.Show
End Sub
Hans Passant
thanks... I just made some tweaks in your code, and it works! Thank you :)
yonan2236