The Windows Forms Model
Forms in Visual Basic 6.0 were distinct files from other types of code (such as modules and classes) stored in two partsa .FRM file that contained the code and the layout of the form and a .FRX file, which was a special kind of resource file that held any embedded resources needed by the form. When you designed a form using the visual tools, controls were added to forms and properties were set (such as the size and position of various controls) without any visible effect on your code. Changing the position of a button would change some hidden (not shown in the IDE at least) text (shown below for a simple one button "Hello World" application) that you could access and change using a text editor, but all of these properties were not part of your code. Setting a property in code was therefore very different than setting it through the visual interface.
Listing 3.1 The Code Behind a Visual Basic 6.0 Form
VERSION 5.00 Begin VB.Form Form1 Caption = "Form1" ClientHeight = 3090 ClientLeft = 60 ClientTop = 450 ClientWidth = 4680 LinkTopic = "Form1" ScaleHeight = 3090 ScaleWidth = 4680 StartUpPosition = 3 'Windows Default Begin VB.CommandButton Command1 Caption = "Hello World" Default = -1 'True Height = 495 Left = 840 TabIndex = 0 Top = 480 Width = 1335 End End Attribute VB_Name = "Form1" Attribute VB_GlobalNameSpace = False Attribute VB_Creatable = False Attribute VB_PredeclaredId = True Attribute VB_Exposed = False
This special area of the form would also contain object references (in the form of GUIDs) for any ActiveX controls you used. Although editing the .FRM file directly was not encouraged, that was exactly what you had to do to fix a corrupt form.
Forms in .NET change everything just described. Forms are no longer "special" files; they are just code (.VB files in .NET), although they certainly can have associated resource files with them. Editing the properties of the form or of the controls on the form does not add hidden text to the form file; it generates real VB .NET code that sets the properties in the same way that you would in your own code. If you follow along with me and create a sample VB .NET form, you can explore the new forms designer and browse the code generated by your visual editing.
Building a Hello World Sample
First, go ahead and fire up Visual Studio .NET. Although it is possible to create Visual Basic .NET applications without using any IDE (another example of how VB has changed in its move to .NET), this book assumes that you have at least VB .NET Standard Edition and are therefore using the Visual Studio IDE.
Once it is loaded, you should see a start page. This start page has a few tabs and several different areas of information, but the main area (which is displayed by default) has all of the functionality you need at this point, including a list of recently opened projects and a New Project button. Click the New Project button, or select File, New, Project from the menu to bring up the New Project dialog box.
If you are new to Visual Studio .NET, this dialog box contains a lot more options than the equivalent from Visual Basic 6.0, including the capability to create Web Services, Windows Services, Console Applications, and more. For now though, pick the standard project for creating a new Windows Application: Windows Application. Selecting this project type (and picking a name and location, and then clicking OK) creates a new solution containing a single project that contains one blank Windows form and a code file called AssemblyInfo.vb. At this point, if you look around the Visual Studio .NET IDE, you will see an interface that is somewhat similar to Visual Basic 6.0, but many things have changed. In the first chapter of this book, I covered the IDE, detailing the key changes from Visual Basic 6.0 and many of the important features.
Moving along with this quick sample, you will build the application's user interface by placing a button onto the form. To work with the form, you need to use its design view, which is accessed through the same steps as in VB6. Double-click the form (in the Solution Explorer) to bring it up in the design view or right-click it and pick View Designer (this was View Object in VB6, but the meaning is the same) from the context menu.
Once you have the form's design view up, you can use the toolbox to select controls and place them onto your form. The toolbox looks a little different from the one in VB6. It has sliding groups to categorize all the different types of controls and lists the controls with an icon and text by default. It works a little differently as well. When you worked with the toolbox in Visual Basic 6.0, you had two choices of how to interact with it:
You could double-click a control and a new instance of that type of control would be added to the form with a default size and location.
You could also select a control and then click the form to set the top-left location and drag an outline out to represent the size of the control.
In the Windows forms designer, you have those two methods of placing a control and an additional option:
You can drag a control from the toolbox onto the desired location on your form and it will be placed at that position with a default size.
Using any one of the three possible methods, place a single button from the toolbox onto the form. It is a minor change, but it is worth noting that the CommandButton control from Visual Basic 6.0 has changed to the Button control in VS .NET 2002 and 2003. Just like in Visual Basic 6.0, you can double-click this new button to start writing an event handler for its most common event (in this case Click). All you want to do is pop up a message box, which you can do with the exact same line of code that you would use in Visual Basic 6.0 (see Listing 3.2).
Listing 3.2 Hello World Does Not Look Too Different in .NET
Private Sub Button1_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles Button1.Click MsgBox("Hello World!") End Sub
You can run the project at this point if you want; F5 works fine for that purpose or you can select Start from the Debug menu. The real reason for building this form was to look at the code generated by your actions in the designer.
Exploring the Designer Generated Code
Switch to the code for the form (right-click the form in the designer or the Solution Explorer and select View Code) and you will see your button's click procedure and an area called Windows Form Designer generated code, as shown in Figure 3.1.
Figure 3.1 Regions allow you to hide blocks of code.That area is a region, a new feature of the code editor in Visual Studio .NET that allows you to collapse areas of code down to a single line to simplify the experience of browsing code. We discussed regions in Chapter 1, but all you have to know now is that the designer (the visual tool for creating forms) has used this feature to hide all of the code that it generated as you built the form. As a rule, you are not supposed to go into this area of code, which is why it is hidden by default, but you should at least understand the code in this area. In some cases, you might even need to change it. You can expand the designer code region by clicking the plus symbol next to the region name.
Inside the region, you will find a few key elements:
A constructor for the form (a Sub New())
A Dispose procedure
Declarations of all of the controls on the form
A sub called InitializeComponent
The Constructor and the Dispose routines are new to Visual Basic .NET, but they are relatively equivalent to the Class_Initialize and Class_Terminate events of Visual Basic 6.0 classes. The constructor is called when an instance of your form is created; the dispose is called before the form is destroyed. The real meat of the designer-generated code is the other two code elementsthe list of declarations for all of the controls on the form and the InitializeComponent routine that sets up the properties of the controls on the form and of the Form itself. You did not set up many controls or even change many properties when creating this simple sample, but let's take a look at the generated code, shown in Listing 3.3.
Listing 3.3 In VB .NET, You Can View and Even Edit All the Code that Builds Your Form's Interface
'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 Button1 As System.Windows.Forms.Button <System.Diagnostics.DebuggerStepThrough()> _ Private Sub InitializeComponent() Me.Button1 = New System.Windows.Forms.Button Me.SuspendLayout() ' 'Button1 ' Me.Button1.Location = New System.Drawing.Point(96, 88) Me.Button1.Name = "Button1" Me.Button1.TabIndex = 0 Me.Button1.Text = "Button1" ' 'Form1 ' Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13) Me.ClientSize = New System.Drawing.Size(292, 273) Me.Controls.Add(Me.Button1) Me.Name = "Form1" Me.Text = "Form1" Me.ResumeLayout(False) End Sub
The comment on the top of this routine lets you know that you can modify anything in here by using the visual designer, and that you should not change the code directly. This is pretty good advice, but let's ignore it for a moment and see what happens. If you look at lines 12-15 in Listing 3.3, you can see that they are setting the properties of the button, including the size. If you add some of your own code in there, even something as simple as outputting some text to the debug window, it could produce surprising results.
In this case, just adding a line (see Listing 3.4) causes the Windows Form Designer to fail when trying to parse the code, producing the helpful little error message shown in Figure 3.2.
Listing 3.4 Editing the Windows Forms Designer Generated Code May Produce Unexpected Results
' 'Button1 ' Me.Button1.Location = New System.Drawing.Point(96, 88) Me.Button1.Name = "Button1" Debug.WriteLine("Testing!") Me.Button1.TabIndex = 0 Me.Button1.Text = "Button1"Figure 3.2 The Windows Forms Designer does not deal well with someone changing its code.
Other, less fatal, changes to the code are often undone the next time you change something in the designer (because the InitializeComponent procedure is regenerated), which can be quite frustrating. Code generators (such as the designers in Visual Studio .NET) work well in many situations, but when they have to support round tripping (where the code isn't just generated once; it is read back in and used by the designer whenever the form needs to be displayed), they tend to be very fragile. In this case, you cannot make code changes to most of the designer-generated area. The place where you can change code is in the constructor; you can freely add code after the call to InitializeComponent as long as you do not remove that line! The best bet is to ignore all of the code inside this special region, other than the constructor, and make all of your property changes through the visual interface. Now let's go back to the button's click procedure and take a closer look at how .NET is handling events.