I'm using the following code to show a form:
How to not duplicate this form? Instead, I'd like to show the opened one.VB Code:
Dim frm As New Form1() frm.Show()
Thanks.
Printable View
I'm using the following code to show a form:
How to not duplicate this form? Instead, I'd like to show the opened one.VB Code:
Dim frm As New Form1() frm.Show()
Thanks.
Make frm a global variable and use frm.Visible = True/False.
This allows only one instance of the current form :
VB Code:
'allows one instance of the form named Form1 Static counter As Integer = 0 If counter = 0 Then Dim frm As New Form1 frm.Show() counter += 1 Else Exit Sub End If
You can also use this:
VB Code:
Static frm As Form1 If frm Is Nothing Then frm=New Form1() 'create Else frm.Activate() 'bring to front End If
I've been trying the same code Edneeis for many times but still generating new instances . Use Show Method and see how many instances you'll get .:confused:
How about using a shared member in the form? I can't try this out right now, but it should work. One of the problems with using a static (instead of a global) is that instances of the form can be created from other modules or forms.
VB Code:
Shared InstanceCount As Integer Sub New() If InstanceCount > 0 Then Me.Show Else InstanceCount += 1 MyBase.New Endif End Sub
Yeah I forgot the show line, but it worked fine for me. You have to make sure you you call that same procedure everytime to start the form though.
VB Code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Static frm As Form4 If frm Is Nothing Then frm = New Form4 'create frm.Show() Else frm.Activate() 'bring to front End If End Sub
Should have used Exit Sub, like this...
VB Code:
Shared InstanceCount As Integer Sub New() If InstanceCount > 0 Then Exit Sub Else InstanceCount += 1 MyBase.New Endif End Sub
Good one, Edneeis, but how to set "frm" to "Nothing" when this form close?Quote:
Originally posted by Edneeis
Yeah I forgot the show line, but it worked fine for me. You have to make sure you you call that same procedure everytime to start the form though.
VB Code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Static frm As Form4 If frm Is Nothing Then frm = New Form4 'create frm.Show() Else frm.Activate() 'bring to front End If End Sub
Thanks.
You don't, you just let the GarbageCollector do its thing and take out the garbage. You can still catch any events you need on the form if you have to dispose of anything manually.