Search code examples
vb.netformsmdi

Vb.net Winforms MDI multiple instance of form open


I want to know that how open multiple form in MDI parent form without duplicate same instances? For example: License Form and User Form open at the same time without duplicate.

       For Each f As Form In Application.OpenForms
            If f.Name = "License" Then
                FormOpen = True
                f.Focus()
                Return
            End If

            If f.Name = "User" Then
                FormOpen = True
                f.Focus()
                Return
            End If
        Next

        If FormOpen = False Then
            If e.Node.Name = "License" Then
                Dim license As New License
                license.MdiParent = Me
                license.Show()
            End If


            If e.Node.Name = "User" Then
                Dim license As New User
                license.MdiParent = Me
                license.Show()
            End If
        End If

Here is my code, but it only can open either one form at the same time. Anyone can help?


Solution

  • You can declare a public boolean variable in a module to avoid duplicates every time you open your forms. If you succeed opening the forms that variable stores the "True" value; if don't it stores false. You also have to store "False" to the variable in the Closed event of each form.

    Below it is the source code:

    Private Sub MDIParent1_Load(sender As Object, e As EventArgs) Handles MyBase.Load User.MdiParent = Me License.MdiParent = Me End Sub

    Private Sub OpenLicenseAndUserFormsToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles OpenLicenseAndUserFormsToolStripMenuItem.Click
        If bool = True Then
            Exit Sub
        End If
        Try
            For Each f As Form In Me.MdiChildren
                If f.Name = "License" Then
                    Dim frm As New License()
                    frm.MdiParent = Me
                    frm.Show()
    
                End If
    
                If f.Name = "User" Then
                    Dim frm As New User()
                    frm.MdiParent = Me
                    frm.Show()
    
                End If
                bool = True
            Next
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        End Try
    
    End Sub