Anatomy of the Visual Basic Code Behind Windows Forms
When you select Windows Application from the New Project dialog box, a solution is created with a Visual Basic project in it. This project contains references and one class, which is called Form1.vb.
Note To see the namespaces imported by default, see the Project Properties dialog box. To access this, right-click the project in Solution Explorer, choose Properties, then Imports from the panel on the left side.
If you look at the default code in this class, you will find the following:
Public Class Form1 Inherits System.Windows.Forms.Form
Note The following code is contained within a region by default.
#Region " Windows Forms Designer generated code " Public Sub New() MyBase.New() ' This call is required by the Windows Forms Designer. InitializeComponent() ' Add any initialization after the InitializeComponent() call. End Sub ' Form overrides dispose to clean up the component list. Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean) If disposing Then If Not (components Is Nothing) Then components.Dispose() End If End If MyBase.Dispose(disposing) End Sub ' Required by the Windows Forms Designer. Private components As System.ComponentModel.Container ' NOTE: The following procedure is required by the Windows Forms Designer. ' It can be modified using the Windows Forms Designer. ' Do not modify it using the Code Editor. <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent() components = New System.ComponentModel.Container() Me.Text = "Form1" End Sub #End Region End Class
- InitializeComponent: Used by the development environment to persist the property values you set in the Windows Forms Designer. In previous versions of Visual Basic, this information was not saved as code but as textual statements at the top of the .frm file that were always hidden from the developer.
- Public Sub New(): The class constructor. While you can put initialization code for the form here, the best place for initialization code is in the form's Load event.
Note In earlier versions of Visual Basic, you would place initialization code for a form in the Form_Initialize event procedures. The constructor replaces this event. When the constructor begins executing, all of the controls have been sited on the form and initialized.
Use the Properties window to view and manipulate the class name, the name of the class the form inherits from, the access level (
Protected), whether other forms can inherit from this form, and any special attributes the form may have.