Using the Form Class


Visual Basic .NET Unleashed
By Paul Kimmel
Table of Contents
Chapter 15.  Using Windows Forms

Using the Form Class

The Form class in System.Windows.Forms is the control that you will use to design graphical user interfaces. The Form class is a bona fide class in Visual Basic .NET, rather than something slightly different, as it was in VB6.


In Visual Basic 6, it's the Attribute VB_PredeclaredId = True statement that you don't see in a VB6 form that instructs the VB6 compiler to create an autoinstance of a VB6 form. In fact, if you open a VB6 .CLS file with a text editor and modify this Attribute, VB6 will autocreate your classes too.

The project settings stored in the .vbproj fileStartupObject = "ShapedForm. Form1"define the object or class that will be autocreated in Visual Basic .NET. You will have to write a slightly modified version of the code you wrote in VB6 to work with multiform Windows applications. In this section, we will take a look at how to construct instances of forms and some of the useful features of the Form class and how the new IDE helps you work more efficiently . (Chapter 16, "Defining User Interfaces," will cover advanced topics on interface design.)

Creating an Instance of a Form

Assume that you have a two-form application in VB6. Also, assume that Form1 is the startup form, and Form2 is the second form. VB6 allowed you to write Form2.Show when you wanted to display Form2 as a modal dialog box; all you had to do was call Form2.Show vbModal. (You could optionally pass an owner argument as a second argument to Show.)

Visual Basic .NET doesn't support this autocreated use of forms. In VB6, again, if you want to create a second or third instance of a form, you need to declare a variable of the form type, invoke a new instance, load the form, and then show it. Listing 15.7 contains an example demonstrating both styles of showing VB6 forms.

Listing 15.7 Visual Basic 6 allowed you to use an autocreated instance of a form or create a new instance
  1:  Private Sub CommandShow_Click()  2:  Dim F As Form2  3:  Set F = New Form2  4:  Load F  5:  F.Show  6:  End Sub  7:   8:  Private Sub CommandShowModal_Click()  9:  Call Form2.Show(vbModal)  10:  End Sub 


Visual Basic .NET doesn't support autocreated forms. You will have to use the create, use, and release modality for forms in Visual Basic .NET.


You don't have to show a form to use the methods and properties on that form.

The CommandShowModal_Click event from Listing 15.7 demonstrates reliance on an autocreated Form2. The CommandShow_Click handler demonstrates how to explicitly create a new instance of Form2, and then load and show that new instance. It's the latter explicit creation of a form and showing it that you will have to do in Visual Basic .NET.

The code for creating a form is very similar to VB6 but much abbreviated: Dim AForm As New Form2() is equivalent to the Dim, New, and Load form used in VB6.

Showing Forms

Instead of passing parameters to a form in Visual Basic .NET, you can call one of two methods to show a form. Show takes no parameters and displays a modeless form. ShowDialog has two versions. The first version requires no arguments, and the second takes an argument that implements the IWin32Window interfacea form being an example of a class that implements IWin32Windowand returns a System.Windows. Forms.DialogResult enumerated value indicating the action taken to close the form. The following two examples demonstrate creating a form and showing both modeless and modal.

 Dim F As New Form2 F.Show() Dim F1 As New Form2() If (F1.ShowDialog() = DialogResult.Cancel) Then   MsgBox(DialogResult.Cancel.ToString) End If 

The first two statements create and show Form2 using an object named F. The last four state-ments create a second instance of Form2, named F1 and show the dialog modally. (The ShowDialog() method used is the overloaded instance that requires no arguments.) If the user clicks the Cancel button, the enumerated Cancel value is displayed in a message box.

Getting the Modal Result

The modal result when you call ShowDialog is one of the enumerated values in the DialogResult enumeration. Return values are contrived by placing buttons on the form or some other control that returns a modal result when the form is closed.

For example, if you want to create a standard dialog box with an OK button, add a Button control to the form and set the Button.DialogResult property to OK in the properties window. If the form was displayed using ShowDialog, when the user clicks OK, the form will close and ShowDialog will return DialogResult.OK.

Designing the User Interface

User interfaces are easier to design in Visual Basic .NET for many reasons. We will go into greater detail in Chapter 16, but here are a few highlights.

Painting Controls on a Form

Painting controls is the process of dragging controls from the toolbox onto a form. Visual Basic .NET supports double-clicking a control in the toolbox, which causes the IDE to add the control to the form, and simply clicking on the control and once on the form.

If you click a control in VB6 and then click the form once, nothing happens. In Visual Basic .NET, when you click the form, the control is painted using the default size described by the control's constructor; now you get an intuitive behavior. And, of course, as is true with VB6, you can drag the control to any size and position as you are painting the control on the form.

Docking Controls on a Form

Many controls in Visual Basic .NET have a Dock property. Click the drop-down button in the Properties window and the visual dock guide is displayed. Click a button in the Dock editor, and the control will be docked , or aligned, relative to the organization shown in the Dock editor (see Figure 15.8).

Figure 15.8. The Dock property editor allows you to visually control the placement of controls in Visual Basic .NET.


Use the Dock property rather than code to control the location and alignment of controls on Windows Forms.

Managing Controls on a Form

This version of Visual Basic doesn't require you to create a control array. When you copy and paste a control, you get a new instance of the control with cloned properties, with a few differences. The most important difference is that the copied control is an independent object.


You won't be prompted to create a control array in Visual Basic .NET, nor do you need one.

In effect, all controls on a formor on the parent control, like a Panelhave a Controls collection property. When you paint a control, a reference is added to the Control collection and Windows Forms uses these object references to manage the controls and propagate messages to the controls.

If you create controls at runtime with code, you will need to add those dynamic controls to the owning control's Controls collection before the dynamic control will be painted.

Creating Controls Dynamically

Creating a control at runtime is identical to creating any other object: Declare an instance and invoke the constructor. The biggest difference where controls are concerned is that you need to insert the control into the parenting control's Controls collection. Listing 15.8 demonstrates how to dynamically create a button on a form.

Listing 15.8 Dynamically create a button with code
  1:  Private Function UniqueName() As String  2:  Static I As Integer = Controls.Count + 1  3:  I += 1  4:  Return String.Format("Button{0} ", I)  5:  End Function  6:   7:  Private Sub CreateButton(ByVal ButtonToCopy As Button)  8:  Dim B As New Button()  9:   10:  B.Size = ButtonToCopy.Size  11:  B.Location = ButtonToCopy.Location  12:  ButtonToCopy.Dispose()  13:   14:  B.Name = UniqueName()  15:  B.Text = String.Format("{0}  ({1})", _  16:  "Create Button", B.Name)  17:   18:  AddHandler B.Click, AddressOf Button2_Click  19:  Controls.Add(B)  20:  End Sub  21:   22:  Private Sub Button2_Click(ByVal sender As System.Object, _  23:  ByVal e As System.EventArgs) Handles Button2.Click  24:   25:  CreateButton(sender)  26:  End Sub 

The refactored code in the listing calls a method CreateButton when the Button2_Click event occurs (line 25). Instead of writing the code to perform the type conversion from the sender Object to a Button, use a method call and perform the conversion implicitly. (This is safe if you know that the event sender object is a specific type.) In addition to avoiding the CType conversion call, there is a well-named method in its place, CreateButton.

CreateButton creates a new Button control and copies the original button's Size and Location, and then disposes of the original button. A query method, UniqueName, is used to provide a well-named method to assist in getting a unique control name. UniqueName uses a Static variable and begins incrementing beyond the highest-numbered control. (This isn't a perfect method, but works in the example.) The name of the button is added to the button's caption, the Text property, to illustrate that we have a new control object. The handler that invoked this method is added to the new button's Click event, and the control is added to the form's Controls collection.

Each time you click the button in the sample program, it's replaced with a new one with the same functionality and in the same location.

Assigning Event Handlers to Dynamic Controls

The WithEvents statement is used to associate an event handler to an object at compile time. When you are adding event handlers at runtime, use the AddHandler and RemoveHandler statements to associate event handlers with objects. Keep in mind that a single event is a multicast delegate, meaning that an event can invoke more than one handler per event. (Read Chapters 8 and 9, "Understanding Delegates," for more on event handlers.)

Finding the Active Form

Every form has an ActiveForm property. This property will return a reference to the form that has the focus or Nothing if no form is active.


You might have noticed that a lot of code listings don't use the Form's reference to self, Me. Me is implied but if you aren't sure of the members of a form, type the Me reference and IntelliSense will display the members of the Form class.

When you have a modal dialog box displayed, that will be the active form. However, modeless and MDI forms allow you to show and switch between forms with one or more forms remaining open. If you are executing code in one form and need to find the active form, use the Form.ActiveForm property.

Adding Code to Forms

When you add a new form to your project, you are adding a class. A class is a class is a class, in Visual Basic .NET. This means that you can add the same elements to your form classes that you would add to any other class.

The purpose of a form is to support a graphical metaphor for the behavior supported by that form. However, this doesn't mean that all behavior should be defined in the form class. It's important and beneficial to separate the classes in the solution domain between those that describe the behaviors of the form and those that provide the underlying solution. (Refer to Chapter 16 for more on user interface and form design.) For more on the mechanics of adding events, properties, fields, structures, enumerations, and methods to classes, read Chapter 7, "Creating Classes."


Visual BasicR. NET Unleashed
Visual BasicR. NET Unleashed
Year: 2001
Pages: 222 © 2008-2017.
If you may any questions please contact us: