Multiple Forms.

Michaelk

Well-known member
Joined
Jun 3, 2004
Messages
58
Location
Australia
Programming Experience
3-5
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?

Thanks.
 

JuggaloBrotha

VB.NET Forum Moderator
Staff member
Joined
Jun 3, 2004
Messages
4,524
Location
Lansing, MI; USA
Programming Experience
10+
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
 

Michaelk

Well-known member
Joined
Jun 3, 2004
Messages
58
Location
Australia
Programming Experience
3-5
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.

Thanks
 

Paszt

Staff member
Joined
Jun 3, 2004
Messages
1,500
Location
Raleigh, NC - USA
Programming Experience
Beginner
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:

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

Here's how to overcome that problem:
VB.NET:
'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()
        frm.Show()
        'Begin running a standard application message loop, without a form.
        Application.Run()
    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()
    frm.Show()
    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
        Application.Exit()
    End If
End Sub
 
Top Bottom