A Windows Form is a tool for building a Windows application. The .NET Framework offers extensive support for Windows application development, the centerpiece of which is the Windows Forms framework. Not surprisingly, Windows Forms use the metaphor of a form. This idea was brought forward from the wildly successful Visual Basic 6 environment and supports Rapid Application Development (RAD). Visual Basic .NET marries the RAD tools of VB6 with the scalability and maintainability of a fully object-oriented language.
Visual Studio .NET provides a rich set of drag-and-drop tools for working with Windows Forms. It is possible to build a Windows application without using the Visual Studio Integrated Development Environment (IDE), but it is far more painful and takes a lot longer.
However, just to prove the point, you'll use Notepad to create a simple Windows Form application: a dialog box in which you will display the words "Hello World" and a button with the text "Cancel" (see Figure 13-1).When you click on the button, the application closes.
You start by adding an Imports statement for the Windows Forms namespace:
Imports System.Windows.Forms
The key to creating a Windows Form application is to derive your form from System.Windows.Forms.Form:
Public Class HandDrawnClass Inherits Form
The Form object represents any window displayed in your application. You can use the Form class to create standard windows, as well as floating windows, tools, dialog boxes, and so forth. Microsoft apparently chose to call this a form rather than a window to emphasize that most windows now have an interactive component that includes controls for interacting with users.
All the Windows widgets you'll need (labels, buttons, list boxes, etc.) are found within the Windows.Forms namespace. In the IDE, you'll be able to drag and drop these objects onto a designer, but for now you'll declare them right in your program code.
To get started, declare the two widgets you need, a label to hold the "Hello World" text, and a button to exit the application:
Private lblOutput As System.Windows.Forms.Label Private btnCancel As System.Windows.Forms.Button
You're now ready to instantiate these objects, which is done in the form's constructor:
Me.lblOutput = New System.Windows.Forms.Label( ) Me.btnCancel = New System.Windows.Forms.Button( )
Next you can set the form's title text to Hello World:
Me.Text = "Hello World"
|
Set the label's location, text, and size:
lblOutput.Location = New System.Drawing.Point(16, 24) lblOutput.Text = "Hello World!" lblOutput.Size = New System.Drawing.Size(216, 24)
The location is expressed as a System.Drawing.Point object, whose constructor takes a horizontal and vertical position. The size is set with a Size object, whose constructor takes a pair of integers that represent the width and height of the object.
|
Next, do the same for the Button object, setting its location, size, and text:
btnCancel.Location = New System.Drawing.Point(150, 200) btnCancel.Size = New System.Drawing.Size(112, 32) btnCancel.Text = "&Cancel"
The button also needs an event handler, which you implement with the AddHandler keyword, passing in the address of the event handling method, btnCancel_Click( ):
AddHandler btnCancel.Click, AddressOf Me.btnCancel_Click
This code links your event to the btnCancel_Click( ) method:
Protected Sub btnCancel_Click( _ sender As Object, e As System.EventArgs) Application.Exit( ) End Sub 'btnCancel_Click
Now you must set up the form's dimensions. The form property AutoScaleBaseSize sets the base size used at display time to compute the scaling factor for the form. The ClientSize property sets the size of the form's client area, which is the size of the form excluding borders and titlebar. (When you use the designer, these values are provided for you interactively.)
Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13) Me.ClientSize = New System.Drawing.Size(300, 300)
Finally, remember to add the widgets to the form:
Me.Controls.Add(Me.btnCancel) Me.Controls.Add(Me.lblOutput)
That's it; you just need an entry point to invoke the constructor on the form:
Public Shared Sub Main( ) Application.Run(New HandDrawnClass( )) End Sub 'Main
The complete source is shown in Example 13-1. When you run this application, the window is opened and the text is displayed. Pressing Cancel closes the application.
Imports System.Windows.Forms Namespace ProgVBNET Public Class HandDrawnClass Inherits Form ' a label to display Hello World Private lblOutput As System.Windows.Forms.Label ' a cancel button Private btnCancel As System.Windows.Forms.Button Public Sub New( ) ' create the objects Me.lblOutput = New System.Windows.Forms.Label( ) Me.btnCancel = New System.Windows.Forms.Button( ) ' set the form's title Me.Text = "Hello World" ' set up the output label lblOutput.Location = New System.Drawing.Point(16, 24) lblOutput.Text = "Hello World!" lblOutput.Size = New System.Drawing.Size(216, 24) ' set up the cancel button btnCancel.Location = New System.Drawing.Point(150, 200) btnCancel.Size = New System.Drawing.Size(112, 32) btnCancel.Text = "&Cancel" ' set up the event handler AddHandler btnCancel.Click, AddressOf Me.btnCancel_Click ' Add the controls and set the client area Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13) Me.ClientSize = New System.Drawing.Size(300, 300) Me.Controls.Add(Me.btnCancel) Me.Controls.Add(Me.lblOutput) End Sub 'New ' handle the cancel event Protected Sub btnCancel_Click( _ sender As Object, e As System.EventArgs) Application.Exit( ) End Sub 'btnCancel_Click ' Run the app Public Shared Sub Main( ) Application.Run(New HandDrawnClass( )) End Sub 'Main End Class 'HandDrawnClass End Namespace 'ProgVBNET
Although hand-coding is always great fun, it is also a lot of work, and the result in the previous example is not as elegant as most programmers would expect. The Visual Studio IDE provides a design tool for Windows Forms that is much easier to use.
To begin work on a new Windows application, first open Visual Studio and choose New Project. In the New Project window, create a new Visual Basic .NET Windows application and name it ProgVBNetWindowsForm, as shown in Figure 13-2.
Visual Studio responds by creating a Windows Forms application and, best of all, putting you into a design environment as shown in Figure 13-3.
The Design window displays a blank Windows Form (Form1). A Toolbox window is also available, with a selection of Windows widgets and controls. If the Toolbox is not displayed, try clicking the word "Toolbox," or select View->Toolbox on the Visual Studio menu. You can also use the keyboard shortcut Ctrl-Alt-X to display the Toolbox. With the Toolbox displayed, you can drag a label and a button directly onto the form, as shown in Figure 13-4.
Before proceeding, take a look around. The Toolbox is filled with controls that you can add to your Windows Forms application. In the upper-right corner you should see the Solution Explorer, a window that displays all the files in your projects. Below the Solution Explorer is the Properties window, which displays all the properties of the currently selected item. In Figure 13-4, the button (Button1) is selected, and the Properties window displays its properties.
You can use the Properties window to set the static properties of the various controls. For example, to add text to Label1, you can type the words "Hello World" into the box to the right of its Text property. If you want to change the font for the lettering in the "Hello World" label, you click the button on the Font property (marked with an ellipsis), as shown in Figure 13-5.
Clicking the button for the Font brings up the Font dialog box, as shown in Figure 13-6.
You can provide text in the same way for your button (Button1) by selecting it in the Property window and typing the word "Change!" into its Text property. While you are at it, change the name of the button from Button1 to btnChange, as shown in Figure 13-7.
Once you have the form laid out the way you want, all that remains is to create an event handler for btnChange. Double-clicking the button will create the event handler, register it, and put you in the code editing window, where you can enter the event-handling logic, as shown in Figure 13-8. (To make it easier to read, the event handler is circled in the figure, and the very long header is broken onto multiple lines.)
The cursor is already in place; you have only to enter the one line of code:
Label1.Text = "Goodbye!"
|
Visual Studio .NET generates all the code necessary to create and initialize the components. The complete source code is shown in Example 13-2, including the one line of code you provided (shown in bold in this example) to handle the Change button-click event.
Option Strict On
Imports System
Public Class Form1
Inherits System.Windows.Forms.Form
#Region " Windows Form Designer generated code "
Public Sub New( )
MyBase.New( )
'This call is required by the Windows
'Form 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 Form Designer
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Windows
'Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
Friend WithEvents Label1 As System.Windows.Forms.Label
Friend WithEvents btnChange As System.Windows.Forms.Button
<System.Diagnostics.DebuggerStepThrough( )> _
Private Sub InitializeComponent( )
Me.Label1 = New System.Windows.Forms.Label( )
Me.btnChange = New System.Windows.Forms.Button( )
Me.SuspendLayout( )
'
'Label1
'
Me.Label1.Font = New System.Drawing.Font( _
"Microsoft Sans Serif", 12.0!, System.Drawing.FontStyle.Bold, _
System.Drawing.GraphicsUnit.Point, CType(0, Byte))
Me.Label1.Location = New System.Drawing.Point(24, 16)
Me.Label1.Name = "Label1"
Me.Label1.TabIndex = 0
Me.Label1.Text = "Hello World"
'
'btnChange
'
Me.btnChange.Location = New System.Drawing.Point(200, 200)
Me.btnChange.Name = "btnChange"
Me.btnChange.TabIndex = 1
Me.btnChange.Text = "Change!"
'
'Form1
'
Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
Me.ClientSize = New System.Drawing.Size(292, 266)
Me.Controls.AddRange(New System.Windows.Forms.Control( ) _
{Me.btnChange, Me.Label1})
Me.Name = "Form1"
Me.Text = "Form1"
Me.ResumeLayout(False)
End Sub
#End Region
Private Sub btnChange_Click( _
ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles btnChange.Click
Label1.Text = "Goodbye!"
End Sub
End Class
|
The program in Example 13-2 begins by declaring a Form class, which derives from System.Windows.Forms.Form.
Public Class Form1 Inherits System.Windows.Forms.Form
The Form object represents any window displayed in your application. You can use the Form class to create standard windows, as well as floating windows, tools, dialog boxes, and so forth. Microsoft apparently chose to call this a form rather than a window to emphasize that most windows now have an interactive component that includes controls for interacting with users.
All the Windows widgets you'll need (labels, buttons, list boxes, etc.) are found within the Windows.Forms namespace. Visual Studio .NET declares the label and button for you:
Friend WithEvents Label1 As System.Windows.Forms.Label Friend WithEvents btnChange As System.Windows.Forms.Button
Visual Studio .NET then goes on to initialize these objects in the InitializeComponent( ) method it provides, where it also sets the Location, Name, TabIndex, and Text properties of each control and the size, Name, and Text properties of the form itself:
Private Sub InitializeComponent( ) Me.Label1 = New System.Windows.Forms.Label( ) Me.btnChange = New System.Windows.Forms.Button( ) Me.SuspendLayout( ) ' 'Label1 ' Me.Label1.Font = New System.Drawing.Font( _ "Microsoft Sans Serif", 12.0!, System.Drawing.FontStyle.Bold, _ System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.Label1.Location = New System.Drawing.Point(24, 16) Me.Label1.Name = "Label1" Me.Label1.TabIndex = 0 Me.Label1.Text = "Hello World" ' 'btnChange ' Me.btnChange.Location = New System.Drawing.Point(200, 200) Me.btnChange.Name = "btnChange" Me.btnChange.TabIndex = 1 Me.btnChange.Text = "Change!" ' 'Form1 ' Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13) Me.ClientSize = New System.Drawing.Size(292, 266) Me.Controls.AddRange(New System.Windows.Forms.Control( ) _ {Me.btnChange, Me.Label1}) Me.Name = "Form1" Me.Text = "Form1" Me.ResumeLayout(False) End Sub
The location of each control is expressed as a System.Drawing.Point object, whose constructor takes a horizontal and vertical position.
If you adjust the size of the label and button (by dragging the size handles on the form), you'll find that Visual Studio .NET will add Size properties for each control:
Me.Label1.Size = New System.Drawing.Size(112, 23) Me.btnChange.Size = New System.Drawing.Size(80, 23)
The Size property is set with a System.Drawing.Size object, whose constructor takes a pair of integers that represent the width and height of the object.
Top |