Multiple Forms.


Well-known member
Jun 3, 2004
Programming Experience
Hi. I've written a web browser, but i have one problem.
Due to multiple windows needing to be opened (New Windows), the same form may need to be opened multiple times (e.g Form1), simultaneously. The problem i have is that if the original form, Form1, is closed. Then the whole program closes, therefore closing all other windows. I know in VB.NET 2005 you can select that the program only closes once all forms are closed, but how can i do it in 2003? Is there code that i can run on another form which constantly checks how many instances of Form1 are running, and if this value reaches 0, closes the app?

when you go to open a new window, dont start another instance of the current form, start a whole new copy of the application, so the new window is another instance of your app

look at system.diagnostics.process
Thanks for the reply. I did consider that, but wouldn't that way chew up more mem if there are several windows open? I was thinking that the easiest, and most efficient way would be to have a hidden form checking what forms are loaded. And when all the copies of Form1 are closed, then it closes the app? I just don't know how to check what forms are loaded.

The secret is understanding what happens when you set a form as the startup object. When this is done, the compiler creates a Sub Main procedure similar to the following:

Shared Sub Main()
    Dim frm1 As Form1 = New Form1()
End Sub
Here, the ApplicationContext's mainForm is frm1, when it is closed the application exits.

Here's how to overcome that problem:
'use 'Sub Main' as the Startup Object
Friend Module AppMgr

    Friend iForms As Integer

    <STAThread()> _
    Public Sub main()
        iForms = 1
        Dim frm As New Form1()
        'Begin running a standard application message loop, without a form.
    End Sub

End Module

'Form1 contains a button named cmdNewForm 
'that opens a new instance of Form1

'in Form1:
Private Sub cmdNewForm_Click(ByVal sender As System.Object, _
  ByVal e As System.EventArgs) Handles cmdNewForm.Click
    Dim frm As New Form1()
    iForms += 1
End Sub

Private Sub Form1_Closing(ByVal sender As Object, _
  ByVal e As System.ComponentModel.CancelEventArgs) _
  Handles MyBase.Closing
    iForms -= 1
    If iForms = 0 Then
    End If
End Sub

Latest posts