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
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()
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.
Add the necessary finalization methods:
#Region " Finalization "
ublic Overloads Sub Dispose() Implements
Protected Overridable Overloads Sub Dispose(ByVal disposing As Boolean)
If Not (Me.Disposed) Then
If (disposing) Then
handle = IntPtr.Zero
Me.Disposed = True
Protected Overrides Sub Finalize()
Private Sub MyForm_Closed(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles MyBase.Closed
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.
Private Shared _Instance As MyForm = Nothing
Public Shared Function Instance() As MyForm
If _Instance Is Nothing OrElse _Instance.disposed = True Then
_Instance = New MyForm