26

I give this question for more knowledge. How can I know if the form is Opened in my application or not, in order not to open it again I mean not to create an instance of the same form while it's running

   Dim frmCollection As New FormCollection()
    frmCollection = Application.OpenForms()
    If frmCollection.Item("Form2").IsHandleCreated Then
        MsgBox("Yes Opened")
    Else
        Dim f As New Form2()
        With f
            .Text = "form2"
            .Show()
        End With
    End If

if I executes this code many times it will create more instances of the form Form2 How can I check if this form is not already opened

Matt Busche
  • 14,216
  • 5
  • 36
  • 61
Mohammed Khaled
  • 263
  • 1
  • 3
  • 6

9 Answers9

52

You can try it like this:

 Imports System.Linq ' need to add 


If Application.OpenForms().OfType(Of Form2).Any Then
  MessageBox.Show("Opened")
Else
  Dim f2 As New Form2
  f2.Text = "form2"
  f2.Show()
End If
Georg
  • 404
  • 5
  • 7
LarsTech
  • 80,625
  • 14
  • 153
  • 225
  • Thank you I have also found this code, that helped me, '------------ Public Function isOpened(ByVal frm As Form) As Boolean? Dim frmCol As New FormCollection() frmCol = Application.OpenForms Dim Cnt As Integer = 0 For Each f As Form In frmCol If f.Name = frm.Name Then Cnt += 1 Next Return IIf(Cnt > 0, True, False) End Function '------------------------- Though I found an answer but I'll try yours of course. – Mohammed Khaled Mar 15 '13 at 19:22
  • 1
    I realize this is tagged vb.net, but I stumbled onto this looking for a C# answer. In case anyone else did the same the syntax is: Application.OpenForms.OfType().Any(). Just slightly different than the VB version. – Tony D Oct 08 '13 at 19:55
  • @BrandonWillis You are going to have to give me a scenario where is doesn't. – LarsTech Aug 10 '17 at 19:54
  • Yikers I definitely don't even remember looking at VB.net anymore. lol sorry. – Brandon Willis Mar 11 '19 at 03:31
12

You can use the following code:

If myForm.IsHandleCreated then
   myForm is open
End If
KyleMit
  • 30,350
  • 66
  • 462
  • 664
user3124064
  • 121
  • 1
  • 2
3

As an extension of the answers given (thank you, all), here's a simple way to activate or show:

Dim frmCollection = System.Windows.Forms.Application.OpenForms
If frmCollection.OfType(Of Form2).Any Then
    frmCollection.Item("Form2").Activate()
Else
    Dim newForm2 = New Form2
    newForm2.Show()
End If
HumbleBeginnings
  • 1,009
  • 10
  • 22
3

For more simplicity you may create a public static bool variable which will tell whether the form is opened or not. On form load event assign 'true' and on closed event assign 'false' value.

2

ANOTHER refactoring way from the one initiated by HumbleBeginnings:

    Dim xChildWindows = Application.OpenForms.OfType(Of frmForm2)
    If xChildWindows.Any Then
        xChildWindows.First().Focus() 'Focus if exists
    Else
        Dim xfrmNew As New frmForm2() 'Open window if doeasn't exists
        xfrmNew.MdiParent = Me
        xfrmNew.Show()
    End If
Dave
  • 29
  • 1
1

Hate to be a kill joy but some day some one is going to try and understand your code.

Dim frm as New frmDontknow
Dim frmCollection = System.Windows.Forms.Application.OpenForms
For i As Int16 = 0I To frmCollection.Count - 1I
  If frmCollection.Item(i).Name = frm.Name Then
      frmCollection.Item(i).Activate()
      Exit Sub
  End If
Next i

Then do the show etc as required?

Fobbert
  • 11
  • 3
  • 1
    Can you point out better the code change that solves the problem as distinct from those that improve maintainability? – Nathan Tuggy Oct 25 '15 at 01:05
1

Check if form is Opened, To validate if a form is open we use this method and function to be able to invoke from any form and use less code.

Example : This will use it in a form with mdiContainer and a panel object with 3 buttons that shows the 3 windows form.

Imports System Imports System.Reflection

Private Sub OpenWindowsForm(ByVal FormName As String)
    Dim instForm As Form = Application.OpenForms.OfType(Of Form)().Where(Function(frm) frm.Name = FormName).SingleOrDefault()
    If instForm Is Nothing Then
        Dim frm As New Form
        frm = DirectCast(CreateObjectInstance(FormName), Form)
        frm.MdiParent = Me
        Me.Panel1.Controls.Add(frm)
        Me.Panel1.Tag = frm
        frm.Show()
    Else
        instForm.Select()
        instForm.WindowState = FormWindowState.Maximized
        instForm.BringToFront()
    End If
End Sub

Public Function CreateObjectInstance(ByVal objectName As String) As Object
    Dim obj As Object
    Try
        If objectName.LastIndexOf(".") = -1 Then
            objectName = [Assembly].GetEntryAssembly.GetName.Name & "." & objectName
        End If

        obj = [Assembly].GetEntryAssembly.CreateInstance(objectName)

    Catch ex As Exception
        obj = Nothing
    End Try
    Return obj

End Function

How to use in click events Private Sub btnRegistro_Click(sender As Object, e As EventArgs) Handles btnRegistro.Click OpenWindowsForm("Registro") End Sub

Private Sub btnBusqueda_Click(sender As Object, e As EventArgs) Handles btnBusqueda.Click
    OpenWindowsForm("Busqueda")
End Sub

Private Sub btnCalendario_Click_1(sender As Object, e As EventArgs) Handles btnCalendario.Click
    OpenWindowsForm("Calendario")
End Sub

Here is an image of the Sample code

Kym NT
  • 670
  • 9
  • 28
FERIOS
  • 11
  • 3
0

you can try this

Dim formText As String
Dim prevText As String

 Private Sub OpenForm(ByVal frm As Windows.Forms.Form)
        formText = frm.Text
        If formText = prevText Then Exit Sub
        CloseForms()
        ' Make it a child of this MDI form before showing it.
        frm.MdiParent = Me
        frm.Show()
        frm.Location = New Point(0, 0)
        prevText = formText
    End Sub

    Private Sub CloseForms()
        For Each ChildForm As Form In Me.MdiChildren
            ChildForm.Close()
        Next
    End Sub

    Private Sub NewToolStripButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PayablesToolStripMenuItem.Click
            OpenForm(frmPayables)
        End Sub
  • Welcome to Stackoverflow! When responding to a question that has already been answered 6 other times. It is helpful to include some text about how your answer helps that was not already explained in the previous answers. – buczek Dec 13 '16 at 17:40
  • i just want to share my ideas. to help me as well. – Jun Gie Cas Dec 14 '16 at 12:19
0
For Each frm As Form In Application.OpenForms
    If frm.Name = Form1.Name Then
       MessageBox.Show("Opened")
    End If
Next
  • 2
    Remember that Stack Overflow isn't just intended to solve the immediate problem, but also to help future readers find solutions to similar problems, which requires understanding the underlying code. This is especially important for members of our community who are beginners, and not familiar with the syntax. Given that, **can you [edit] your answer to include an explanation of what you're doing** and why you believe it is the best approach? – Jeremy Caney Apr 18 '22 at 01:27