Allow only one instance of MDI child in your VB.NET MDI application

1 minute read

I have encountered a problem in class today, we needed our Contact Manager application only to run one instance of every MDI child form, so the user will not be able to start unlimited(more than 1) number of Contacts form, or any of the settings forms. I have binged the solution and found a piece of code that allows something like that, but as i am teaching VB.NET here, i had to rewrite it from C# to VB.NET. The original C# Code provided by Roy Osherove is HERE Here is the VB.NET code i have rewritten from Roy’s version:

Imports System
Imports System.Windows.Forms
Imports System.Collections.Specialized
Public Class MdiFormLoader
  Private m_InitializedForms As HybridDictionary = New HybridDictionary()
  Public Sub LoadFormType(ByVal formType As Type, ByVal mdiParentForm As Form)
    If (IsAlreadyLoaded(formType)) Then
    End If
    Dim frm As Form = Activator.CreateInstance(formType)
    frm.MdiParent = mdiParentForm
    AddHandler frm.Closed, New EventHandler(AddressOf FormClosed)
  End Sub
  Private Sub FlagAsLoaded(ByVal formType As Type)
    m_InitializedForms(formType.Name) = True
  End Sub
  Private Sub FlagAsNotLoaded(ByVal formType As Type)
    m_InitializedForms(formType.Name) = False
  End Sub
  Private Function IsAlreadyLoaded(ByVal formType As Type) As Boolean
    Return If(m_InitializedForms(formType.Name), m_InitializedForms(formType.Name) = True)
  End Function
  Private Sub FormClosed(ByVal sender As Object, ByVal e As EventArgs)
    Dim closingForm As Form = sender
    RemoveHandler closingForm.Closed, New EventHandler(AddressOf FormClosed)
  End Sub
End Class

You can call your form by using these 2 lines:

  Dim _formLoader As New MdiFormLoader()
_formLoader.LoadFormType(GetType(ContactsMain), Me)

Categories: ,