posted on Thursday, January 22, 2004 8:15 PM by demiliani

Singleton Pattern for Windows Form: my implementation

Many times on forums and newsgroups there's a question like this: "How can I access a form member from another part of the program?"

A way to do this is to implement the Singleton Pattern. This is how you can do it:

1) Create a Sub Main (like this above) in a module:

Sub Main()
Application.Run(New Form1)
End Sub


2) Add a shared member to the form:

Private Shared instance As Form1

3) Add a function to your form that returns the form instance if it's already created: 

Public Shared Function InstanceObject() As Form1
If (instance Is Nothing) Then
instance = New Form1
End If
Return instance
End Function

4) In the form constructor (after the InitializeComponent) save the form instance on the shared member:

instance = Me

After that, from an other form (or from every part of your code) to access to members, methods or properties of the form instance, you can do like this:

Form1.InstanceObject.Label1.Visible = False

Suggestions or comments?

Comments