Introduction
There may be times when you want to be sure that there is only one instance of a form within your Compact Framework application. You may also need to be able to pass data between open forms. This is why we use the singleton design pattern. You may have used this in a standard Windows application, but a Compact Framework application is a bit trickier.
Preparing the Form
The first thing that you will need to do is add an explicit implementation of the IDisposable
interface. This is something that you do not have to do with a Windows form, however it will be necessary with a Compact Windows Form.
Public Class MyForm
Inherits System.Windows.Forms.Form
Implements IDisposable
....
Next, you will want to change the constructor of the form to Private
. This makes sure that you cannot mistakenly create a new instance of the form from anywhere else:
Private Sub New()
MyBase.New()
InitializeComponent()
End Sub
Go ahead and remove the Protected Overloads Overrides Dispose
method while you're there.
Next, you'll need to add two internal members:
Private handle As IntPtr
Private Shadows disposed As Boolean = False
*You have to declare the disposed member as Shadows
because it would conflict with a member of the base class component.
Finalization
Add the necessary finalization methods:
#Region " Finalization "
Public Overloads Sub Dispose() Implements
IDisposable.Dispose
Dispose(True)
GC.SuppressFinalize(Me)
End Sub
Protected Overridable Overloads Sub Dispose(ByVal disposing As Boolean)
If Not (Me.Disposed) Then
If (disposing) Then
End If
handle = IntPtr.Zero
End If
Me.Disposed = True
End Sub
Protected Overrides Sub Finalize()
Dispose(False)
End Sub
Private Sub MyForm_Closed(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles MyBase.Closed
Me.Dispose()
End Sub
#End Region
Shared Instance
Now, the last part. You'll need to add an Instance
method to act as your shared entry point for the form. This should go directly after the constructor.
...
End Sub
Private Shared _Instance As MyForm = Nothing
Public Shared Function Instance() As MyForm
If _Instance Is Nothing OrElse _Instance.disposed = True Then
_Instance = New MyForm
End If
_Instance.BringToFront()
Return _Instance
End Function