Writing Windows Forms Applications in Visual Studio .NET 2003
For more information on .NET, visit our .NET Reference Guide or sign up for our .NET Newsletter.
The ability to rapidly develop and deploy forms-based applications is what led to the phenomenal success of Visual Basic. Visual Basic enables you to build enterprise-level applications at lightning speed without requiring you to fully understand what the underlying infrastructure of the operating system is doing. With .NET, this ability is taken to the next level. The Windows Forms model for .NET is fully integrated into the .NET Framework. The development model is fully object oriented, enabling you to create better applications faster using Visual Studio .NET. The rapid in Rapid Application Development (RAD) has never been truer when developing with Windows Forms. Today, you learn about
Using forms and controls
How to handle events in Windows Forms
Adding controls to forms
Dynamically adding controls to Forms
Creating MDI applications with Windows Forms
Inheriting Windows Forms
Using common dialogs in Windows Forms
Hello .NET!
Every introduction to writing applications needs to start with the Hello World type application. This isn't because it's such a cool cliché. It's to get you familiar with the environment you're working in and to better explain what's going on when you're running the application. To get you started with Visual Studio .NET development, you're going to create the HelloNET application.
To begin, start Visual Studio .NET. On the Getting Started page, click the New Project button. You're prompted with the New Project dialog you learned about yesterday. Figure 3.1 demonstrates the New Project dialog.
Figure 3.1 The New Project dialog box.
Select the Windows Application template from either the C# or Visual Basic folder, and change the Name to HelloNET. Click the OK button to create the application.
After the project has been created, you should be looking at something like Figure 3.2.
NOTE
Throughout this book, there are code examples for Visual Basic .NET and C# for everything you learn. When I ask you to create a new application, most of the time I say to call it something_vb or something_cs, depending on the language you're writing your code in. To differentiate the code in the downloads for the book and to enable you to write the same application in both languages, you can't have the same project name. So, if there are screenshots that look like a project name is different from what I ask you to create, that's the reason. By the end of the book, you'll see there's very little difference between C# and Visual Basic .NET, and you'll be bilingual!
Figure 3.2 The HelloNET application.
As you learned yesterday, there are many useful windows when developing applications. The key items you'll use when creating Windows Forms applications are the Solution Explorer, the Properties window, and the Toolbox. If you don't see these windows on your screen, you can get to them in the ways shown in Table 3.1.
Table 3.1 Shortcuts to Main Windows When Designing Forms
Window |
Shortcut Options |
Properties |
F4 key |
View, Properties from the View menu |
|
The Properties button on the standard toolbar |
|
Toolbox |
Ctrl+Alt+X shortcut keys |
View, Toolbox from the View menu |
|
The Toolbox button on the standard toolbar |
|
Solution Explorer |
Ctrl+Alt+L shortcut keys |
View, Solution Explorer from the View menu |
|
The Solution Explorer button on the standard toolbar |
The key to rapid development with Windows Forms is the ability to easily drag items from the Toolbox onto the forms, set properties on the controls that you add using the Properties window, and write code that responds to the controls and form events. That's why the three windows in Table 3.1 are so important.
Next, you must add some controls to the form. From the Toolbox, drag a Button control, Textbox control, and Label control to the form that's in the Windows Forms designer. Your form should look something like Figure 3.3 after the controls are added.
TIP
There are a couple of other ways to add controls to a form. First, you can double-click Toolbox controls to add them to a form. They are added on top of the last control added to the form. The second way is to select a control from the Toolbox and "draw" it onto the form with your mouse. This will let you position and size the control as you add it to the form.
Figure 3.3 Adding controls to the default form.
Next, single-click the form and press the F4 key to view its properties. Change the following properties on the form:
StartPosition: CenterScreen
MaximumSize: 400, 400
MinimumSize: 200, 200
Font: Tahoma, 14pt
After you set the Font property, notice that the font sizes of the controls on the form change to the form's font properties. This is a new feature in Windows Forms; the controls inherit the font properties of the form. You can easily override these properties by setting properties on the individual controls. You learn more about the different controls a little later.
Next, double-click Button1 to get to the Code Editor window. This works like Visual Basic 6 did: You double-click controls and you're taken to their default event.
You're now looking at the Form_Load event. Notice that the load event accepts two argumentsSystem.Object and System.EventArgsas the following code snippet demonstrates:
VB.NET
Private Sub Form1_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load End Sub
C#
private void Form1_Load(object sender, System.EventArgs e) { }
Every control that you add to a form (and the form itself) always has to accept the object that's passing it the data and then the event arguments for that object. Depending on the control and the event, it won't always be System.EventArgs, but there will always be an event arguments parameter.
In the Form_Load event, add the code in Listing 3.1, which displays a message box welcoming you to Visual Studio .NET.
Listing 3.1 The Form_Load Event Code for HelloNET
VB.NET
Private Sub Form1_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load MessageBox.Show("Welcome to .NET!") End Sub
C#
private void Form1_Load(object sender, System.EventArgs e) { MessageBox.Show("Welcome to .NET!"); }
You'll notice that the MessageBox class is used to prompt information back to the user. The functionality of the MessageBox class is very similar to that of the MsgBox function in Visual Basic 6. You can pass a prompt, respond to button events, and set the title for the message box that's displayed.
Next, you need to add code for the click event of the Button you added to the form earlier. There are several ways to write code that responds to events in Windows Forms. The easiest way to write code for an event is to double-click a control on the Forms Designer and you're taken to the default event for that control in the Code Editor.
If you're writing in Visual Basic, you can select the control from the Class Name drop-down list in the upper-left corner of the Code Editor. After you select the control you want to write an event for, you can select the correct method from the Method Name drop-down list, which is next to the Class Name drop-down list. Figure 3.4 demonstrates the Method Name drop-down list for some of the Button1 events. Notice that Button1 was selected from the Class Name list.
Figure 3.4 The Button1 Method Name options.
You'll also notice the (Overrides) and (Base Class Events) options in the Class Name drop-down. The (Overrides) option gives you all the methods, properties, and events that you can programmatically override for the form. The (Base Class Events) option gives you the methods for the Form class. A little later today you'll better understand how classes work and what they'll mean to you as you develop not only in Windows Forms, but also in .NET as a whole.
If you're a C# developer, you don't have the Class Name and Method Name drop-down lists in the Code Editor for events that haven't been added to the form. To add new events for the form and for controls on the form, you must select the control on the form while you're in the Forms Designer. Then, on the toolbar of the Properties window for the selected control, click the lightning bolt button, which gives you the list of events for the selected control. When you find the event you want to write code for, you can double-click the event name in the list, and you're taken to the Code Editor for that event. Figure 3.5 demonstrates the button1_Click event selected in the Properties window.
Figure 3.5 The button1_Click event of the Properties window for a C# application.
Now that you know how to add events with the IDE, add the code in Listing 3.2 to the button1_Click event.
Listing 3.2 button1_Click Event for the HelloNET Application
VB.NET
Private Sub Button1_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Button1.Click Label1.Text = TextBox1.Text End Sub
C#
private void button1_Click(object sender, System.EventArgs e) { label1.Text = textBox1.Text; }
There are a few items to note on the code you just wrote:
The Text property is used for both the Label and the TextBox control. This is different from Visual Basic 6. There is no longer a Caption property for labels, forms, or other controlsit's replaced with the Text property.
C# is a case-sensitive language, and the casing defaults to camel casing, meaning that the first character of an object name is lowercase and the first letters of any subsequent concatenated words are uppercase. Visual Basic uses Pascal casing, meaning that the first character is uppercase and the first letters of any subsequent concatenated words are uppercase.
-
Visual Basic automatically fixes the casing of object names, but C# does not. This also means the auto-list members do not work in C# if the casing isn't correct. Figure 3.6 demonstrates auto-list members in C# when the casing is correct. Auto-list members works in Visual Basic even if the casing is incorrect.
Figure 3.6 Auto-list members in the C# Code Editor.
Now that the code has been added and you're getting an idea of how to work with the IDE, press the F5 button to run the application. Pressing F5 has the same effect as selecting Start from the Debug menu or clicking the Start button on the Standard toolbar.
When the application starts, you're prompted with Welcome to .NET! that you added in the Form_Load event. After the form is active, type Hello .NET into the TextBox and click the Button on the form. The Label control is filled with the contents of the TextBox.
You also set some properties in the form, such as MinimumSize, MaximumSize, AutoScroll, and StartPosition. When the application starts, the form shows up in the middle of the screen. If you now resize the form, you'll see that it can only grow to a certain size and shrink to a certain size. This is a cool feature that wasn't in Visual Basic 6. The bigger-than-life feature is AutoScroll. If you resize the form and the controls can't remain visible, scrollbars appear automatically. Figure 3.7 demonstrates AutoScroll in action.
Figure 3.7 The AutoScroll property for a form in action.
You can click the X in the upper-right of the form to close the form and get back to the designer.
NOTE
When you're in the integrated development environment (IDE) and press the F5 key to run the application, you're in Debug mode. In Debug mode, the application is running and you have access to all the debugging features in Visual Studio .NET that you learn about on Day 7, "Exceptions, Debugging, and Tracing." When you stop debugging, by closing the main form that is running or clicking the Stop button on the Debug toolbar, you go back to Design time. So, when you're writing an application in the Visual Studio .NET IDE, you're either in Debug mode or Design time mode. When the application is compiled and you run it from the file system, it's called runtime.
The AutoScroll property is one of many cool properties that forms and controls have in .NET. To see some of the new properties, follow Table 3.2 and change the corresponding properties.
Table 3.2 Properties to Change on the Form1 Controls
Control |
Property |
Value |
Form1 |
Name |
frmMain |
Opacity |
80% |
|
FormBorderStyle |
SizeableToolWindow |
|
SizeGripStyle |
Auto |
|
Text |
Wow This Is Great! |
|
TopMost |
True |
|
Button1 |
Anchor |
Top, Left, Right |
Cursor |
Hand |
|
FlatStyle |
Flat |
|
BackColor |
SteelBlue |
|
Text |
Click Me! |
|
ForeColor |
LightGray |
|
Name |
ClickMe |
|
Label1 |
Dock |
Bottom |
TextAlign |
BottomRight |
|
Textbox1 |
CharacterCasing |
Upper |
MultiLine |
True |
|
AcceptsReturn |
300,300 |
|
Anchor |
Top, Bottom, Left, Right |
|
Size |
292, 140 |
|
Location |
28, 68 |
|
TextAlign |
Right |
|
Cursor |
Cross |
After you've changed the properties for the controls, press the F5 key to run the application. Figure 3.8 shows the form after typing some text in the box and resizing the form.
Figure 3.8 Running the HelloNET application after changing object properties.
You'll notice some very cool things happening with this form:
It is almost invisible. The Opacity property can be set anywhere from 0% to 100%, which makes the forms see-through. When the TransparencyKey property on the form is set, all controls that contain the color set in the TransparencyKey are 100% transparent. Try it out!
Setting the Dock property on the Label control glues it to the bottom of the form. All controls can be docked in Windows Forms.
Setting the Anchor property automatically resizes the control when the form is resized. This is automatic, and every control in Windows Forms can be anchored. No more resize code!
The ScrollBars are no longer there. Because the Anchor and Dock properties are set on the form, there's no need to scrollthe controls always resize within the bound of the form.
The Cursor property is easily changed for all controls in Windows Forms. This enables you to customize the look and feel for each control when the mouse hovers over it.
The text in the Textbox is UPPERCASE, and the words display from right to left. You can use the Enter key inside the Textbox. Setting the CharacterCasing, AcceptsReturn, and TextAlign properties allow complete customization of the Textbox control.
The form stays on top of all other open applications. Using this property in conjunction with the Opacity property can give you some great options for always-open, nonintrusive applications.
Besides making a form that has no real use, the goal of setting the properties for the controls on the form was to introduce you to some of the cooler features of Windows Forms. When you changed properties such as Anchor, Dock, Cursor, and TextAlign, you learned that the Properties window options are visual and easy to use. In addition to the many new properties coming from a Visual Basic 6 environment, using the Properties window is easier than ever. As usual, the description for each property is still visible on the lower portion of the Properties window, so you don't need to press the F1 key for help when you're not sure about a property's functionality.
TIP
Hopefully, you see the power of Windows Forms. The Opacity property used in conjunction with the TransparencyKey property has a great use if you're a consultant or a company providing demo software. You can literally make the form, or controls on the form, disappear before the viewer's eyes by using the properties correctly.
Let's say you have 20-day demo software and after the 30 days, the user must purchase the full version. Each day, starting with day 1, you could reduce the Opacity property by 5%. By the 20th day, the application would be literally invisible, so the user has to pay the money for the full version. If you're a consultant and you're worried about getting paid, just randomly change the Backcolor of controls to the same TransparencyKey color. When you do so, the controls become transparent, making it appear that data is disappearing. After the customer pays up, you can modify the code to be more user-friendly!
Now that you have your feet wet with the IDE, you can learn about how the applications you write using Windows Forms actually work.
NOTE
When working with controls on a form, you can select multiple controls with the Ctrl+click combination. After you've selected multiple controls, you can set properties on all the selected controls at the same time. You can also use Shift+click to select multiple controls, just like you would in Windows Explorer to select multiple files.