«^»
7. Windows Forms applications

Standalone programs that read and/or write to a command shell window are boring: over the years, Visual Basic has led the way in making it easier to produce programs that have a graphical user interface (GUI).

Although it is possible to construct these programs yourself with a text editor, it is a lot easier to use one of Visual Studio.NET's wizards.

If, from within Visual Studio.NET, you choose the Windows application template, Visual Studio.NET will present a Form and invite you to add GUI components to the Form from a Toolbox.

Suppose we want a program that records the arrivals and departures of vehicles from a carpark. To the Form, we could add:

As you add GUI components to the Form, behind the scenes the wizard is adding code to a file called Form1.vb.

One key thing it does is to create variables in the program for each of the GUI components: they will be called TextBox1, Button1, Button2 and Label1.

Having added the GUI components to the Form, you can double click each button in turn. When you double click a button, Visual Studio.NET will open up the code of the Form1.vb file positioning you in the midst of the method responsible for handling clicks of that button. So if you double click the first button, it will put you in the body of a method called Button1_Click. You can then add the code you want executed when that button is clicked.

So I just provided lines 216 and 221 of the following code:

0128: Public Class Form1
0129:     Inherits System.Windows.Forms.Form
0130: 
0131: #Region " Windows Form Designer generated code "
0132: 
0133:     Public Sub New()
0134:         MyBase.New()
0135: 
0136:         'This call is required by the Windows Form Designer.
0137:         InitializeComponent()
0138: 
0139:         'Add any initialization after the InitializeComponent() call
0140: 
0141:     End Sub

          ...

0212: #End Region
0213: 
0214:     Private Sub Button1_Click(ByVal sender As System.Object, _
0215:             ByVal e As System.EventArgs) Handles Button1.Click
0216:         Label1.Text = TextBox1.Text + " has arrived"
0217:     End Sub
0218: 
0219:     Private Sub Button2_Click(ByVal sender As System.Object, _
0220:             ByVal e As System.EventArgs) Handles Button2.Click
0221:         Label1.Text = TextBox1.Text + " has departed"
0222:     End Sub
0223: 
0224: End Class

When we are using Visual Studio.NET, a lot of this code is hidden from us: on the screen, it is in the region labelled Windows Form Designer generated code. You can click on the + button in order to reveal the contents of this region.

You should be careful about altering the contents of this region. If you change the GUI components of the Form, it will automatically change the code of this region. Similarly, if you are clever enough to edit the code of the region to add the code for a new GUI component and it understands what you have done, it will automatically alter the contents of the Form.