Your Privacy Matters: We use our own and third-party cookies to improve your experience on our website. By continuing to use the website we understand that you accept their use. Cookie Policy
20
Singleton Pattern On Specific MDI Children
posted

Is there a more efficient way of implementing a singleton pattern on mdi child forms? Here is what I have...

I created a custom form class that inherits from a Form...

Imports System.Windows.Forms
Imports System.ComponentModel

Public Class CustomMDIChildForm   
        Inherits Form
    

Private
_singletonOnly As Boolean = False
     <Browsable(True)> _

Public Property SingletonOnly() As Boolean
        Get
            Return _singletonOnly
        End Get
        Set(ByVal value As Boolean)
            _singletonOnly = value
        End Set
    End Property 

End Class

I inherit this when creating a form I know will be an MDI child...

Public Class frmSomeMDIChildForm
    Inherits CustomMDIChildForm
  ...
  ..
  .

 
End Class

Then in my parent form, I have this method....

Public Sub LoadMDIForm(ByRef theForm As CustomMDIChildForm)

       
Me.Cursor = Cursors.WaitCursor
       
       
Dim sStatus = "Loading " & theForm.Text & " functionality..."
       
       
ToolStripStatusMessages.Text = sStatus
       
       
Me.Refresh()
       
       
Dim bFoundSingleton As Boolean = False
        Dim sForm As CustomMDIChildForm = Nothing
        
        
' If the form is only supposed to be a singleton.
        If theForm.SingletonOnly Then
             ' Check first if one is already loaded.
            For Each sForm In Me.MdiChildren
                '   If found, make it selected.
                If sForm.Name = theForm.Name Then
                    bFoundSingleton = True
                    Exit For
                End If
            Next
            If bFoundSingleton Then
                sForm.Activate()
                theForm = sForm
            Else
                With theForm
                    .MdiParent = Me
                    .Dock = DockStyle.Fill
                    .Show()
                End With
            End If
        Else
            '   Not a singleton, so load up a new instance of the form.
            With theForm
                .MdiParent = Me
                .Dock = DockStyle.Fill
                .Show()
            End With
        End If
         Me.Cursor = Cursors.Default
        ToolStripStatusMessages.Text = String.Empty

   End Sub

This works great, but not sure if this is a good approach.

BTW: I'm using ByRef because I have other funky stuff I am doing for specific forms, like selecting a specific datagrid row on a singleton form.

Any feedback is appreciated,

Paul

  • 2334
    posted
    My only suggestion would be to hash the singleton forms as you add them. If you throw a singleton form in the a hashtable as you add it you can then look it up more efficiently that by looping over the MDIChildren.