KnowDotNet Visual Organizer

New to .NET - Why does my application quit when I exit Sub Main?

Migration - Form Loading Differences in .NET

by Les Smith
Print this Article Discuss in Forums

I am new to VB.NET, coming from VB6.  Why does my application quit after loading a form from Sub Main?

Form loading is different in VB6 and .NET, whether VB.NET or C#.  In NET, forms are not loaded directly as they were in VB6.  Rather, you must create an instance of the form and then use the Show method of the form object.  Many people, new to .NET, do the following in Sub Main, which worked in VB6, but not in VB.NET.

Module Module1
  
Public Sub Main()
      
Dim frm As New Form1
      frm.Show()
  
End Sub
End
Module

In this case, an instance of Form1 will flash on the screen and the application will quit as soon as the Form_Load method is completed (even faster if there is no Form_Load event).  What's the problem?

The problem is that "frm" is a local instance of an object, that is disposed as soon as Sub Main is exited.  There are two ways to solve this problem.  The first is shown below:

Module Module1
  
Public Sub Main()
      
Dim frm As New Form1
      frm.ShowDialog()
  
End Sub
End
Module

However, the preferred method is shown next.

Module Module1
  
Public Sub Main()
      
Dim frm As New Form1
      Application.Run(frm)
  
End Sub
End
Module

Writing Add-Ins for Visual Studio .NET
Writing Add-ins for Visual Studio .NET
by Les Smith
Apress Publishing