Windows Forms
Objectives
• Create Windows applications using the command line compiler. • Create Windows applications using Visual Studio .NET. • Explore Windows controls and Windows Forms.
• Set properties on forms and controls. • Create event handlers for Windows Forms. • Use XML comments to generate documentation.
Creating Windows Applications
The entire reason to learn C# is to build applications. Otherwise, this is all an academic exercise in computer science. While C# may one day be a cross platform language, for the immediate future its principal (if not only) reason to exist is to support development on the .NET platform.
.NET applications come in three flavors: Windows Applications, Web Applications and Web Services. This chapter will focus on Windows Applications.
There was a time, not very long ago, when the distinction between a desktop application and a Web application was clear and unmistakable. Today, and increasingly, these distinctions are blurring. Many desktop applications integrate with the Web. For example, Microsoft’s Street’s and Tips program uses the Web to update its list of construction delays, and Norton’s Antivirus program is fully integrated with the Web to keep itself up to date with the latest virus cures.
Web applications, on the other hand, are doing more and more work on the client, further reducing the distinction between Web and Windows
applications. In the final analysis, the real distinction is this: who is responsible for the User Interface? If the UI is a browser showing HTML sent from a server, it’s called a Web application; otherwise it’s called a desktop application.
In .NET, Windows desktop applications are built using Windows Forms. The goal of Windows Forms is to bring the Rapid Application Development environment made famous in Visual Basic 6 to C# and other .NET application languages.
The model is quite simple: you create a form object that derives from System.Windows.Forms.Form. You then create controls, such as
System.Windows.Forms.Label or System.Windows.Forms.Button. You set the text, location, and size of your controls and then set up event handlers. The event handlers are compiled in what is known as a code behind page. Finally, you add the controls you’ve created to your form’s controls collection and you run the application, passing in the form to the application’s Run method.
Writing Windows Apps by Hand
As a rule, you will write your Windows Applications in Visual Studio .NET. This integrated Development Environment (IDE) offers tremendous support for building windows applications quickly and painlessly. The forms builder alone will save you many hours of hand-coding your application.
That said, there is nothing magical about the IDE and you are certainly free to write your applications by hand, using nothing more than a simple text editor and the command line compiler.
Try It Out!
To prove this to yourself, write your first Windows application in Notepad.
1. Open Notepad and create a new file. Save it as HelloWorld.cs. 2. Add two using statements to the top of the file to inform the compiler
which namespaces you’ll be using in this application.
using System;
using System.Windows.Forms;
These designations simply save you time. Rather than having to declare your Label object as
System.Windows.Forms.Label output
you can add the using System.Windows.Forms designation to the top of the file and then just write:
Label output
3. Create your form class (myForm), and derive from the System Form class:
public class myForm: Form {
4. Add two controls as private member fields. One is a Label, while the other is a Button.
See
// a label to display text private Label output; // a cancel button private Button cancel;
5. Create the class constructor. In the constructor you’ll start by initializing your controls.
public myForm() {
// create the objects output = new Label (); cancel = new Button ();
6. The title on the form is held as a member field Text; you can set that to something appropriate.
// set the form's title
Text = "Hello World From Windows";
7. You are now ready to set the location, size, and text for the output label.
// set up the output label
output.Location = new System.Drawing.Point (20, 30); output.Text = "Hello World From Windows!";
output.Size = new System.Drawing.Size (200, 25);
Because you are doing this by hand, you must set the Location by hand. You do that by creating a Point object, passing in the coordinates (20,30) for the object, and passing that Point object to the Location property of the control. Set the size of the control by creating a System.Drawing.Size object, passing in the size to the constructor. This size struct is then assigned to the Size property of the control.
// set up the cancel button
cancel.Location = new System.Drawing.Point (150,200); cancel.Text = "&Cancel";
cancel.Size = new System.Drawing.Size (110, 30);
9. You must assign an event handler to the Click event of the button. This uses events and delegates as explained elsewhere in this course.
// set up the event handler cancel.Click +=
new System.EventHandler (this.OnCancelClick);
You’ve told the compiler that Click events for the button will be handled by the OnCancelClick method, which you will write in just a moment.
10. Add the controls to the form’s Controls collection.
// Add the controls Controls.Add (cancel); Controls.Add (output);
11. That completes the constructor. You now need only to write the OnCancelClick method that you’ve wired as the event handler for the button. When the user clicks the Cancel button you want to exit the application. You do this with the static Exit method of the Application class.
// handle the cancel event protected void OnCancelClick(
object sender, System.EventArgs e) {
Application.Exit(); }
By convention, all Windows events take two parameters. The first, of type object, represents the control sending the event (in this case the button). The second is an object of type EventArgs that provides additional information about the event. In the case shown here, neither parameter is used in the event handler.
12. All that is left is to start the application. Like all C# applications, this one begins with a static method Main. In this static method you’ll call the static Run method of the Application, passing in a new instance of the form you’ve just created.
// Run the app
public static void Main() {
Application.Run(new myForm()); }
Build the Application:
13. Save the file as HelloWorld.cs and close the file in Notepad.
14. To build the application navigate to the Visual Studio .NET program group and choose Visual Studio Tools. Within the Tools group choose Visual Studio .NET Command Prompt. This opens a Command window with the environment set properly for building .NET applications.
15. Navigate to the directory in which you’ve saved your file. Take a directory; you should see just HelloWorld.cs.
16. Enter csc HelloWorld.cs.The compiler prints a message and returns a command prompt.
17. Type dir to get a directory listing; you should now see HelloWorld.exe. 18. Type HelloWorld and the application opens, as shown in Figure 1. The application is quite simple; the label displays your text and the button is drawn waiting for you to click it.
Figure 1. Running HelloWorld.
Writing Windows Apps with
Visual Studio .NET
While that wasn’t very difficult, large applications are quite tedious to craft by hand. Visual Studio .NET makes the task much easier, as you’ll see in the next exercise.
Try It Out!
To see how much easier it is to work with Visual Studio, you’ll write the same application again, this time using the IDE to drag the controls onto a form.
1. Open Visual Studio .NET and click on New Project.
2. Under Project Types, choose Visual C# Projects and under Templates choose Windows Application. Name the project HelloWorldVS, as shown in Figure 2. Click OK to create the project.
See
Figure 2. Creating a new project.
3. A new project is created. Depending on how your system is configured, you should see the Toolbox open on the left, a form designer in the center, and the Solution Explorer and Properties window on the right, with a number of windows available at the bottom, as shown in Figure 3. If any of these windows are not open, you can open them from the View menu or the Debug window. If the Toolbox does not appear, but a small rectangle with the word Toolbox is visible in the upper left, click on the rectangle, the Toolbox should open. You can then pin it in place, using the Pushpin icon.
Figure 3. Visual Studio .NET windows.
4. Drag a Label to the form. Place it where you’d like it.
5. Use the Properties window to set the text property of the label to Hello World From Windows!
6. Drag the label to size it big enough to hold the text.
7. Drag a button onto the form. Set its text property to Cancel.
8. Drag the button to where you want it on the form, then click on the form and resize it to the size you want.
9. Double-click on the button to open its Click event handler. Visual Studio brings you to the code-behind page in the button1_Click event handler. It has already wired the handler for you; no need to do that by hand. 10. Add the code for the event handler, just as you did previously.
private void button1_Click(
object sender, System.EventArgs e) {
Application.Exit(); }
11. Press CTRL+F5 to run the application. The application starts up and the window opens, as shown in Figure 4. You can press Cancel to close the application and return to the development environment.
Figure 4. Running the application from Visual Studio .NET
Enhancing Your Application
You can see that even with the world’s simplest Windows application, Visual Studio .NET has made your life a lot easier. You are ready now to enhance this application a bit. There is a tremendous amount you can do; this chapter will only highlight a few of the tools available.
Try It Out!
To get started, just modify the existing application to see how you can add features with very little effort.
1. Reopen the project from the previous example.
2. Click on the form itself, and go to the Properties window. Set the name of the form to HelloWorld and set the Text to Hello World From
See HelloWorld WindowsVSNET. sln
Windows!. When you leave the Text property, you should see the title of the Form change.
3. Click on the BackColor attribute in the Properties window. A dropdown opens. Click on Custom to open a color palette. Choose a pleasing color and you’ll see the background color for the form change to your choice. 4. Click on the label and change the text to HelloWorld. Change the name to
lblHello. Click on the font attribute and set the font to Comic Sans MS. Set the size to 14.
5. Change the text on the Cancel button to Bye and add a second button with the text ChangeText. Name the new button btnChange. Move both buttons to the upper left of the form.
6. Click on the first button, then shift click on the second to select them both. Use Format|Make Same Size to make the buttons the same size. Use Format|Align to align the two buttons on their left sides, then use Format|Vertical spacing to space the buttons.
7. Click on the form to show its sizing handles, and resize the form, so that it looks like Figure 5. Feel free to adjust the form to fit your own aesthetic sensibilities.
Figure 5. Resizing and formatting the form.
8. You are ready to wire up the event handlers. Double-click the Bye button and verify that the code has not changed in the event handler.
9. Return to the designer and double-click on btnChange. You are now in the event handler for the btnChange click event. Add the following text:
lblHello.Text = "Goodbye world!";
When the user clicks on the btnChange button the text in the label will change.
10. Navigate in the page behind to find the Main method. Change the argument to run to new HelloWorld.
static void Main() {
Application.Run(new HelloWorld()); }
You renamed the form, and you must use the new name of the form when you create it. Scroll up to see that the name of the class was changed as well, and that it is an instance of this newly-named class that you are creating.
public class HelloWorld : System.Windows.Forms.Form
11. Build the application and run it. When it opens, click on btnChange to see the effect, as shown in Figure 6. When you click on the btnChange
button, the text in the label is altered. Click Bye to exit the program.
Figure 6. After clicking Change Text.
Controls
The key to Windows Forms applications is the plethora of controls available in the Toolbox. Writing a good Windows application is more than just dragging controls onto a form, but that is a good starting point. Put the right controls on the form and wire up useful event handlers, and you are well on your way to building powerful Windows applications.
This is a course on C# and not on Windows application development, so this chapter just scratches the surface on what is available. Nonetheless, looking at how to build Windows applications provides powerful insight into the utility of the techniques taught in the chapters on language fundamentals.
Try It Out!
To get started, you’ll build a simple form-based application with various controls.
The final product is shown in Figure 7. This is a form that might be used by a salesperson to take an order for a new computer. Choose various options, and when you click Order, the order is summarized in the space below the Order button.
Figure 7. A complex order form. See WinForm
1. Create a new Windows Forms application and name it WinFormControls.
2. Drag a single check box control onto the form and place it where you want it. Name the box chkService and set the text to Full service.
3. Run the application. Your check box is drawn and you can check and uncheck it (though nothing interesting will happen when you do). The result is shown in Figure 8. You don’t get much functionality, but it’s not bad for 30 seconds work.
Figure 8. Testing the check box.
4. Add a group box to the form and make it bigger then you’ll need. 5. Add three radio buttons within the group box (just drag them onto the
group box). Align them more or less one below the other. 6. Name the three radio buttons btnLaptop, btnDesktop,and
btnWorkStation.
7. Set their text to Laptop, Desktop,and Work Station respectively. 8. Shift click through the three buttons to select them all.
9. Choose Format|Align|Lefts to align their left-hand edges.
10. Choose Format|VerticalSpacing|MakeEqual to set equal spacing between all three controls.
11. Choose Format|VerticalSpacing|Increase (or decrease) if you need to change the amount of space between the controls. Keep the vertical spacing fairly tight.
12. Move the three buttons to the upper left of the group box and resize the group box to fit.
13. Click on the group box and change its text to Computer Type as shown in Figure 9.
Figure 9. Setting the group box.
14. Click on the rbDesktop control and set its checked property to true. When you run the application, this button will default to checked. Run the application to test it, as shown in Figure 10. You are free to click on other buttons, but this way the default choice is Desktop.
Figure 10. Testing the radio button checked property.
15. Drag a button onto the form, and name it btnOrder. Set its text to Order. 16. Lengthen the form to make room, and drag a label under the order button. Name the label lblOutput. Widen the label and lengthen it to hold a good bit of text. Delete the text in its text property (so that it is blank).
17. Double-click on btnOrder to set the event handler. You want to assemble the output string. Start by creating a string named output. Add code to test whether the chkService check box is checked. If so, modify the output string:
string output = "Your order...\n"; if (chkService.Checked == true)
output += "You ordered the full in-house service\n";
18. Add code to the event handler to check which radio button is checked, and to modify the output accordingly.
if (rbLapTop.Checked)
output += "Laptop computer\n"; else if (rbDeskTop.Checked)
output += "Desktop computer\n"; else
19. Add code to display the results in the label.
lblOutput.Text = output;
20. Run the program to test it. Click on choices and click Order to see the results displayed in the label, as shown in Figure 11. If the output is wrapping where you don’t expect, or is cut off, you may need to expand the label field.
Figure 11. Testing the button event handler.
Get It Working/Keep It Working
The approach you are taking with this application is a very powerful design approach: get something working and keep it working. Rather than adding all the controls, setting all the properties and then trying the program, you are adding small changes and repeatedly testing. This is a very effective way to write complex applications.
Events
When you double-clicked the Order button you went to the event handler for the OnClick event. This is the default event for the button, but of course button supports many other events. To see how to wire up other events, click on the button and then click on the lightning bolt button in the Properties window. A list of events is shown, as illustrated in Figure 12. You are free to fill in the
name of event handlers for any of the events. For example, type in the name OnDragDrop next to the DragDrop event and press ENTER. You are taken to the OnDragDrop event handler.
Figure 12. Events for the button.
If you made a mistake and did not want to create this event, just go back to the form and delete it from the events list.
Do not delete the event handler in the code-behind or you’ll leave behind the code that adds the method to the event. You can remove that by hand, but it is cleaner to let the IDE do it for you.
Adding More Controls
To see how some of the other controls work, you’ll add a few more controls to the application you created in the previous Try It Out.
Try It Out!
1. Add a checked list box and name it cblFeatures. You’ll probably have to lengthen the form and move the list box and Order button out of the way. See WinForm
2. You will want to populate the list box when the form is created. To do this, double-click on the form. This opens the default event handler for the form, Form1_Load. This is the event that fires when the form is loaded. 3. Add code to the Form Load event handler to populate the list box. The list
box has a member Items, which is a collection of the items in the list. You can add to that collection using the AddRange method that takes an array of objects. You’ll pass in an array of eight strings:
cblFeatures.Items.AddRange( new object[8] {
"Monitor", "Tape backup",
"Zip drive", "Modem", "Extra Ram", "Speakers", "CD", "CDRW"
} );
4. Modify the order_click event handler to pick up the choices made by the user. The check box list contains a list of items that are checked,
CheckedItems. You can iterate over that list with a foreach loop, adding each string to the output. Modify the event handler to look like the following:
private void btnOrder_Click(
object sender, System.EventArgs e) {
string output = "Your order...\n"; if (chkService.Checked == true) output +=
"You ordered the full in-house service\n"; if (rbLapTop.Checked)
output += "Laptop computer\n"; else if (rbDeskTop.Checked)
output += "Desktop computer\n"; else
output += "Workstation computer";
foreach (string s in cblFeatures.CheckedItems) output += "Feature: " + s + "\n";
lblOutput.Text = output; }
5. Build and run the application. Click on various features and then click Order. The results should look something like Figure 13.
Figure 13. Testing the check box list box.
6. You can add a regular (not checked) list box in much the same way. Drag a list box onto the form and name it lbModel. Once again, populate this in the form load event:
for (int i = 0; i<20; i++) {
lbModel.Items.Add("Model X" + i); }
This creates model numbers such as ModelX0, ModelX1, and so forth. 7. Adjust the event handler for the button to display the model.
if (lbModel.SelectedIndex != -1) output += "Model: " +
lbModel.Items[lbModel.SelectedIndex] + "\n";
If no item is checked, the SelectedIndex property of the list box will be –1, otherwise the SelectedIndex property can be used as an index into the Items collection of the list box.
8. You’ll add one more control: a combo box to list the salesperson taking the order. Drag a combo box onto the form, and name it cbSalesPerson. 9. Initialize the combo box in the form load event handler.
cbSalesperson.Items.AddRange( new object[4]
{ "Jesse", "Mr. Galt", "Milo", "JW" } );
Once again you are filling the list from an array of Strings. This time, however, you want to set the text for the drop-down list box to a prompt that is not in its list of choices.
10. Set the Text property of the combo box to Choose Sales Person.
cbSalesperson.Text = "Choose sales person";
11. Add code in the button event handler to pick up the choice of salesperson.
if (cbSalesperson.Text != "Choose sales person") output += "Sold by: " + cbSalesperson.Text + "\n";
12. Test the application. Click on the various features and then click Order, as shown in Figure 14. You should see a summary of all your choices in the label below the Order button.
Figure 14. Testing the controls.
Color and Font Properties
While the form works, it doesn’t look great. The job of laying out a truly professional-looking form is beyond the scope of this book (and beyond my capabilities!) but there are some properties you can use to add color to your form. For example, you can set the background color of the list boxes, change the text color of the text itself, and change the font as shown in Figure 15.
Figure 15. Adding a splash of color.
Date/Time Picker
This chapter has barely scratched the surface on the various features and attributes of these controls and these are only some of the standard controls available to you. There is also a suite of new sophisticated advanced controls provided by the Frameworks. In this section you’ll take a look at just one: the DateTimePicker control.
The purpose of the DateTimePicker control is to provide easy access to dates and times (as you might guess). You’ll use it to add a control for setting the delivery date of the order you are building.
Try It Out!
You’ll make one minor modification to the form you just built, adding the new control and using it to set the delivery date.
1. Reopen the project you were just working on. 2. Expand the form to make room for the new control.
3. Drag a dateTimePicker control onto the form. Name the dateTimePicker object dpDelivery.
4. The dateTimePicker has a number of powerful properties. You’ll take control over the format of the date by setting the Format property to Custom.
5. Set the CustomFormat field to MMMM dd, yyyy – dddd. This causes the date to be displayed as, for example, July 10, 2005 – Sunday.
6. In the Order buttons’ on click method, add the following line.
output += "Delivered on " +
dpDelivery.Value.ToString("MM/dd/yy (dddd)") + "\n";
This formats the delivery date to the date and day, as shown in Figure 16. See Controls.sln
Figure 16. Formatting the DateTime
Using the Documentation
All of this is great, but how would you possibly figure out how to do this with the dateTimePicker if this book didn’t tell you? Visual Studio .NET comes with documentation. Look up the dateTimePicker class in the Help index and click on All Members. Scroll down to the value property and click on that. You see that the Value property returns a DateTime object. Click on DateTime in the Help file and scroll down to the bottom. One of the links is DateTime Members. Click on that link. One of the instance methods is ToString. Click on that link and you’ll see that it is overloaded. One of the overloaded versions
takes a string. Click on that and you’ll see that the string is named format. The documentation then provides all the formatting characters and what they mean.
Getting Started
You dragged a number of controls onto the form and added event handlers as required. You set properties to change the look and feel of the form. There is much more you can do to make this form useful, but that is beyond the scope of a course on C#. Before going on, however, you may want to play with the form, add new controls, and get a sense of what power lies in this development environment.
XML Documentation
You’ve seen in previous chapters that C# offers both the traditional C-style comments,
/* this is a comment */
and the more modern C++ style comments:
// this is a comment
C-style comments can span lines and can be used to comment-out entire sections of code.
There is a third type of comment in C#—the XML comment:
/// this is an xml comment
XML comments begin with three slashes and run to the end of the line. XML comments are used to document your code, and with the right tools, these can be used to generate extensive documentation pages.
You can use compile times switches to generate an XML document based on your XML comments and you can use XSL to transform these comments into any kind of document you’d like. Visual Studio .NET also provides built-in support for XML comment documentation.
Try It Out!
To see how XML comments work, return to the previous example and add XML comments to document the file.
1. Reopen the previous example.
2. Scroll to the top of the file and modify the documents above the declaration of the form.
See WinForm Controls.sln
/// <summary>
/// Form for accepting computer orders /// </summary>
public class Form1 : System.Windows.Forms.Form
3. Scroll down to the Form1_Load event handler and type three slashes before the method header. A summary comment springs open. Add a summary within the summary tags and add a description of the parameters within the param tags:
/// <summary>
/// Event handler for Form loading /// </summary>
/// <param name="sender">The form itself</param> /// <param name="e">EventArgs structure</param>
4. Add a comment block above the event handler for the button click.
/// <summary>
/// Button is clicked event /// </summary>
/// <param name="sender">The button</param> /// <param name="e">Struct with info about the event</param>
private void btnOrder_Click(
object sender, System.EventArgs e) {
5. When you are done commenting, choose the menu items Tools|Build CommentWebPages.A dialog box opens as shown in Figure 17. Leave the defaults and click OK.
Figure 17. Building Comment Web pages.
6. A page is created for each project. In this case there is only one project, WinFormControls, as shown in Figure 18.
7. Click on the report for WinFormControls. Click on the + sign next to WinFormControls and the forms are displayed. Click on the Form1 link to show the report about Form1, as shown in Figure 19. Each of the controls have links to documentation, as do all the methods you commented or that were commented automatically by Visual Studio .NET.
Figure 19. The report for Form1.
8. Click on btnOrder_Click. You are taken to a page with information about this method, including its parameters. The descriptions you added in the params element is shown here, as shown in Figure 20.
Figure 20. The btnOrder_Click Function.
It’s Just HTML
The reports themselves are just HTML. To see this, open an Explorer window and navigate to the directory for your project. You’ll find a
CodeCommentReport directory with a number of images in it. Within that directory you’ll find a ControlForm directory filled with htm files that represent the various reports you are viewing.
Really, It’s XML
The HTML pages were generated from the XML file you created based on the comments. You can also see the XML file itself.
1. Open the project in Visual Studio .NET and click on the project in the Solution Explorer.
2. Choose View/Property Pages. 3. Click on Configuration Properties.
4. Set the XML documentation file property as shown in Figure 21. You may name the XML Documentation File anything you wish.
Figure 21. Setting the XML Documentation File. 5. Rebuild the application.
6. Navigate to the directory for your project. You should find a file XMLComments.xml (or whatever it is you named the file in Step 4). 7. Double-click the file. A browser opens with the XML for the comments
you added, as shown in Figure 22. It is this file that is used to generate the HTML report. Typcially the file is not saved after the report is generated, unless you set the file name as shown in Step 4.
Summary
• There are three types of applications you can build using C# and .NET: Windows applications, Web applications, and Web Services. • Windows applications are built using Windows forms.
• Windows Forms provide a Rapid Application Development (RAD) environment in which you can drag controls onto a form.
• You create event handlers for the controls on your form. The Visual Studio .NET Integrated Development Environment (IDE) will help with wiring the event handlers.
• If you double-click on a control the IDE creates an event handler for the default event.
• You can access alternative events using the lightning bolt button on the properties window.
• List box controls have an Items collection to manage the items listed in the list box.
• The Help documentation can be a powerful resource for understanding the properties and methods of controls.
• You can document your files with XML document comments (///) and then use Visual Studio to generate XML report files.
Questions
1. What is the difference between a Windows application and a Web Forms application?
2. From which class must your Form derive?
3. What is the purpose of the statement Using System.Windows.Forms? 4. How do you add controls to a form?
5. How do you add entries to a list box?
6. What is the method to call to add an array to a list box? 7. How do you generate a report based on your XML comments? 8. How do you generate the XML file itself?
Answers
1. What is the difference between a Windows application and a Web Forms application?
A Windows application uses Windows Forms and is intended to be run on the desktop. A Web Forms application is served by a Web server and uses a browser for its User Interface.
2. From which class must your Form derive?
You must derive all forms from System.Windows.Forms.Form 3. What is the purpose of the statement Using System.Windows.Forms?
The using statement allows you to refer to objects in the System.Windows.Forms namespace without qualifying the namespace; thus you can write Label rather than
System.Windows.Forms.Label. 4. How do you add controls to a form?
You add controls to the form’s Controls collection. 5. How do you add entries to a list box?
You add entries to a list box by modifying the List box’s Items collection.
6. What is the method to call to add an array to a list box?
The List Box’s Items collection has an AddRange method that will take an array of objects.
7. How do you generate a report based on your XML comments?
To generate the report from within Visual Studio .NET you use the menu choice Tools/Build Comment Web Pages.
8. How do you generate the XML file itself?
You generate the XML file by navigating to the PropertyPages for the project and setting the XML Documentation File property under Configuration Properties.
Lab 15:
Lab 15 Overview
In this lab you’ll learn to create Windows Applications using WinForms. To complete this lab, you’ll need to work through three exercises:
• Building a Windows Form without Visual Studio .NET • Creating Hello World Using Visual Studio
• Building Applications with Windows Controls
Each exercise includes an “Objective” section that describes the purpose of the exercise. You are encouraged to try to complete the exercise from the
information given in the Objective section. If you require more information to complete the exercise, the Objective section is followed by detailed step-by-step instructions.
Building a Windows Form without
Visual Studio .NET
Objective
In this exercise, you’ll see that building a Windows Forms application by hand is possible, but not necessarily easy.
Things to Consider
• Your form must inherit from System.Windows.Forms.Form. • You must place each control at a specific location (using
System.Drawing.Point).
• You must size each control (using System.Drawing.Size). • Once you create your controls you must add them to the Form’s
control collection.
Step-by-Step Instructions
1. Open your favorite text editor, such as Notepad or WordPad, and start a new text file. Call it HelloWorld.cs.
2. Add using statements for the namespaces System and System.Windows.Forms.
using System;
using System.Windows.Forms;
3. Create a namespace (optional). Don’t forget the closing brace at the end of the file.
namespace HelloWorld_Completed {
public class myForm: Form {
5. Create a label to display text.
private System.Windows.Forms.Label output;
6. Create a button to cancel (exit).
private System.Windows.Forms.Button cancel;
7. Create the constructor for the myForm class.
public myForm() {
8. Create the objects: a label and a button.
output = new System.Windows.Forms.Label (); cancel = new System.Windows.Forms.Button ();
9. Set the form’s title.
Text = "Hello World From Windows";
10. Set the label’s location to 20,30 (use System.Drawing.Point).
output.Location = new System.Drawing.Point (20, 30);
11. Set the label’s text to Hello World From Windows!
output.Text = "Hello World From Windows!";
output.Size = new System.Drawing.Size (200, 25);
13. Set the button’s location to 150,200 (use System.Drawing.Point).
cancel.Location = new System.Drawing.Point (150,200);
14. Set the button’s text to &Cancel.
cancel.Text = "&Cancel";
15. Set the button’s size to 110,30 (use System.Drawing.Size).
cancel.Size = new System.Drawing.Size (110, 30);
16. Register the click event handler.
cancel.Click += new System.EventHandler
(this.OnCancelClick);
17. Add the controls to the form.
Controls.Add (cancel); Controls.Add (output);
18. End the myForm constructor.
}
19. Implement the click event handler. The only action is to call the static method Application.Exit.
protected void OnCancelClick(
object sender, System.EventArgs e) {
Application.Exit(); }
20. Run the app from Main by calling Application.Run and passing in an instance of the form.
public static void Main() {
Application.Run(new myForm()); }
21. End the class and namespace.
} // end the class myForm } // end the namespace
22. Open the command window for compiling your class. To do so, open the Visual Studio .NET Command Prompt from the Start|Programs|Visual Studio.NET Tools menu as shown in Figure 23.
Figure 23. Choosing the command prompt. 23. Navigate to the directory with your .cs file.
24. Compile the program with the following command:
csc HelloWorld.cs
25. List the directory; you should now find helloWorld.exe as well as helloWorld.cs. Enter the name helloWorld and press ENTER. Your code should run as shown in Figure 24.
Creating Hello World Using Visual
Studio
Objective
In this exercise, you’ll recreate the Hello World application using Visual Studio.
Things to Consider
• Visual Studio writes much of the infrastructure for you, but the fundamentals are unchanged.
• Your form will be separated from your “behind” file. The code-behind will house the event handlers.
• When you place objects on the form, they will be located and sized for you, but you may take explicit control either in the code or through the properties.
Step-by-Step Instructions
1. Create a new Visual C# Windows Application in Visual Studio named WindowsHelloWorld.
2. Drag a label onto the form and set the text to Hello World From Windows!
3. Stretch the label to fit the words.
4. Drag a button onto the form. Name it btnCancel. 5. Set the button’s text to Cancel.
6. Double-click on the Cancel button to open the event handler. 7. Enter the code to close the application in the event handler.
Application.Exit();
Figure 25. The Hello World application.
Building Applications with Windows
Controls
Objective
In this exercise, you’ll create a Windows form for booking a reservation at a hotel.
Things to Consider
• Radio buttons are used to select a single choice among many.
• Check boxes are used to select multiple choices. When you have many check boxes, consider using a check box list.
• Drop-down list controls are good for a single selection among many choices.
• Double-click on a control to set its default event handler.
Step-by-Step Instructions
1. Create a new Windows application named Hotel Reservation.
2. Drag a label onto the form and set its text to Hotel Reservation Form. 3. Set the font size to 14.
4. Set the font to bold.
5. Set the TextAlign property to MiddleCenter.
6. Drag a check box onto the form and name it chkVIP.
7. Set its background color to Green and its text to VIP Customer. 8. Drag a group box onto the form, and set its text to Room Type.
9. Drag a radio button onto the group form, set its name to rbSingle, and its text to Single.
10. Drag a second radio button onto the group form, set its name to rbDouble, and its text to Double.
11. Drag a third radio button onto the group form, set its name to rbSuite, and setits text to Suite.
12. Use the format menu choice to make all three radio buttons the same size, align their left borders, and set their vertical spacing to equal.
13. Resize the group to fit the radio buttons and set the background color of the group to Cornflower blue.
14. Drag a checkedListBox onto the form and set its name to clbFeatures. 15. Click on the Items property and add the following features:
Whirlpool Color TV VCR DVD
On-Demand Movies In-Room Wet Bar Free Breakfast Free Lunch Free Meals Late checkout Early check in
16. Set the Sorted property to true and watch the list sort itself. 17. Set the background color to a pleasing pastel.
18. Add a button named btnBook and set its text to Book Reservations. Stretch the button to fit.
19. Set the button’s background color to red, set its forecolor to yellow, and set its font to bold.
20. Drag a label onto the form. Set its name to lblOutput and its text to blank. Your form should now look more or less like Figure 26.
Figure 26. The hotel reservation form.
21. Double-click on the Book Reservations button to open the event handler. Create a string to hold the output:
string output = "Your reservation...\n";
22. Check if the VIP Customer check box is checked, if so modify the text for the output string.
if (chkVIP.Checked == true) output +=
"VIP Service!\n";
if (rbSingle.Checked)
output += "Single room\n"; else if (rbDouble.Checked) output += "Double room\n"; else
output += "Suite";
24. Add output for each feature that is selected and checked in the list.
foreach (string s in clbFeatures.CheckedItems) output += "Feature: " + s + "\n";
25. Display the output in the label.
lblOutput.Text = output;