Checking to see if a from is open

Jay1b

Contributor
Joined
Aug 3, 2003
Messages
640
Location
Kent, Uk.
Hi

I have a timer event (every second) that checks to see if a condition is true, if so then it raises a form. Currently the program just raises the form every second - which is obviously annoying.

I would like to check if the form is currently running then only create a new instance of it, if it isnt. The code below is in a procedure that is called from the timer event

Visual Basic:
            Dim FrmAllowDis As New FrmAllowDis
            FrmAllowDis.Text = ThisProcess.ProcessName
            'Display the form
            If FrmAllowDis.ShowDialog() = System.Windows.Forms.DialogResult.Yes Then
            End If


Could someone tell me what i am doing wrong pls?

Thanks.
 
Hi again, ive dealt with this before, whereby i wanted to limit the forms instance to 1. Basically i made the following changes to the form i wanted to limit:

if you had 2 forms: Form1 and Form2 and only wanted to show one instance of Form2 no matter how many times a show button was clicked:

Add this to the top of the form2 class:

Visual Basic:
Private Shared objFrmInstance As Form2

Change the default Public Sub New() code to:

Visual Basic:
Private Sub New()

This function goes inside the Form2 Class

Visual Basic:
'If an instance doesnt already exist then set the instance to New Form1
'when called, if an instance isnt already available the calling code can
'create a new instance of the form
    Public Shared Function GetInstance() As Form2
        If objFrmInstance Is Nothing Then
            objFrmInstance = New Form2
        End If
        Return objFrmInstance 
    End Function

Add a button to Form1 and on its click event:

Visual Basic:
        Dim frmForm2 As Form2 = Form2.GetInstance()
        varForm2.Show()
 
Oooops my mistake: You need to add the following code to overide the Forms Closing event so that the instance isnt destroyed, just hiden:

Visual Basic:
  Protected Overrides Sub OnClosing(ByVal e As CancelEventArgs)
    e.Cancel = True
    Me.Hide()
  End Sub
 
Jay1b said:
Tried, tested and works beautifully thank you! :D

Next question: How did you ever think of that?
its typical Design Pattern - Factory

by the way, the proper solution for your problem is:

Protected Overrides Sub OnClosing(ByVal e As CancelEventArgs)
objFrmInstance = nothing
End Sub
 
Back
Top