C# Programming: From Problem Analysis to Program Design, 2nd ed.

Chapter 8 Introduction to Windows Programming At a Glance

Instructor’s Manual Table of Contents ♦ Chapter Overview ♦ Chapter Objectives ♦ Instructor Notes ♦ Quick Quizzes ♦ Discussion Questions ♦ Projects to Assign ♦ Key Terms

8-1

C# Programming: From Problem Analysis to Program Design, 2nd ed.

8-2

Lecture Notes

Chapter Overview In this chapter, students extend their knowledge of programming by creating applications that capture and respond to user input. A different way of programming based on interactively responding to events such as mouse clicks is introduced. Windows-based applications using the .NET Framework Class Library are built. Classes that enable highly interactive, attractive, graphical user interface (GUI) applications are introduced. The drag-and-drop construction approach available with Visual Studio is illustrated.

Chapter Objectives In this chapter, students will: • • • • • • •

Differentiate between the functions of Windows applications and console applications Learn about graphical user interfaces Become aware of some elements of good design Use C# and Visual Studio to create Windows-based applications Create Windows forms and be able to change form properties Add control objects such as buttons, labels, and text boxes to a form Work through a programming example that illustrates the chapter’s concepts

Instructor Notes CONTRASTING WINDOWS AND CONSOLE APPLICATIONS With a console-based application, each line in the Main ( ) method is executed sequentially. Then the program halts. Method calls might branch to different locations in your program; however, control always returns to Main ( ). Programs retrieve data by calling the operating system to get data, and they call on the operating system to output data through method calls such as WriteLine( ) or Write( ). Once launched, the Windows application sits in a process loop waiting for an event— notification from the operating system that an action, such as the user clicking the mouse or pressing a key, has occurred. Instead of calling on the operating system with a request, as console applications do, Windows applications receive messages from the operating system that an event has occurred. Methods called event handlers indicate what should be done when an event occurs.

C# Programming: From Problem Analysis to Program Design, 2nd ed.

8-3

Both console and Windows applications begin execution in the Main ( ) method. However, unlike console-based applications that exit after all statements have been sequentially executed, Windows-based applications, once they are launched, sit idly waiting for notification of a registered event. These event-handler methods may be executed in a different order every time your application runs. The program remains in the operating system environment in the process loop. This means your program could be minimized, resized, or closed like other Windows applications. Windows applications not only function differently, they also look different.

Quick Quiz 1. True or False: Windows applications do not have a Main ( ) method. Answer: False 2. Special methods called ________ _________ are written to indicate what should happen when an event such as a mouse click occurs. Answer: event handlers 3. When a Windows application is executed, it sits in a ________ ____________. Answer: process loop 4. True or False: Windows applications also look different than console-based applications. Answer: True

GRAPHICAL USER INTERFACES Program interaction with console-based applications have been limited to accepting input through the ReadLine ( ) method and displaying output at the DOS console window. The interfaces were not graphical. Windows applications include a graphical user interface (GUI). A graphical user interface (GUI) can include menus, buttons, pictures, and text in many different colors and sizes. These controls can display and respond to user interaction. The form is a container waiting to hold additional controls. Forms have a title bar, complete with an icon on the left, a textual caption in the title bar, and the typical Windows minimize, maximize, and close buttons. Visual Studio Integrated Development Environment (IDE) automatically generates all the code needed for a blank Windows form. Use the built-in, drag-and-drop construction of the IDE to add the controls. Most of the classes for developing Windows-based application are organized in the System.Windows.Forms namespace. Use the using directive to import types or classes from the System.Windows.Forms namespace. Visual Studio automatically adds this reference and imports the namespace when you create a Windows Application Project using the IDE. The class heading definition includes the class name and a colon followed by another class name. The second class is called the base class; the first is called the derived class.

C# Programming: From Problem Analysis to Program Design, 2nd ed.

8-4

The heading added is: public class Form1 : Form The new class inherits all the functionality of the base class. Form is a predefined .NET class that includes a number of methods and properties used to create a basic Windows screen. Windows forms and controls offer a wide variety of changeable properties including Text, Color, Font, Size, and Location. Much of the power of Visual Studio lies in having these properties readily available and easy to change or add through IntelliSense. Text is a property that can be used to set or get the caption of the title bar for the window. Execution for Windows-based programs begins in the Main( ) method. First statement instantiates or creates an object of the Form1 class (Form1 winForm = new Form1( );). Last statement in the body of Main( ) calls the Run( ) method (Application.Run(winForm);). Application class is also defined as part of the System.Windows.Forms namespace. The object that is instantiated from the Form1 class is sent as the argument to its Run( ) method. This Run( ) method call is what displays the form and places the application in a process loop so that it receives messages from the operating system when events of interest to the application are fired. The Exit( ) method stops an application and closes all of its windows.

Quick Quiz 1. What statement places a Windows application in the process loop? Answer: Application.Run(formName); 2. True or False: In a class heading such as "public class Form1 : Form", Form1 is the derived class. Answer: True 3. Identify two Form properties that can be changed. Answer: Text and Font 4. Give three examples of Control objects. Answer: Button, Menu, Label

ELEMENTS OF GOOD DESIGN Appearance matters! The goal should be to develop applications that are usable, that permit users to spot items in the windows quickly, and that enable users to interact with your program. A large field of research, called human-computer interaction (HCI), concentrates on the design and implementation of interactive computing systems for human use. Few HCI considerations include design consideration in the area of consistency, alignment, avoid clutter, color, and the target audience.

C# Programming: From Problem Analysis to Program Design, 2nd ed.

8-5

Consistency Consistent placement of items is important. Consistent sizing of items is important. Consistent appearance of items that are performing the same functionality is also important. Unless you are trying to call attention to an item, keep the item the same as other items. Use contrast to bring attention. Alignment Use alignment for grouping items. When you place controls on a form, place similar items together. They can be lined up to call attention to the fact that they belong together. Avoid Clutter Do not crowd a form with too many controls. Fonts should be large enough to be legible. Color Background colors and foreground text colors should contrast each other. Avoid using bright colors (such as reds), especially for backgrounds—this can result in user eye fatigue. You can use color as an attention getter, but do not abuse it. Color can play a significant role in your design. Target Audience Think about the design of an interface in terms of who will be using it and on what platform it will be displayed.

Quick Quiz 1. True or False: Always try to include as many controls on the form as you can place. Answer: False 2. True or False: Use bright colors on the form to call attention to the controls. Answer: False 3. True or False: Forms should include a maximum of three controls per container. Answer: False 4. Identify three issues that should be taken into consideration when you design a form. Answer: Avoid clutter, think about the intended audience, and be consistent with the placement of controls on the form

USE C# AND VISUAL STUDIO TO CREATE WINDOWS-BASED APPLICATIONS Visual Studio automatically generates code when you create a Windows application. Begin by selecting File>New>Project and selecting Visual C# Project as the Project Type with Windows Application selected from the list of Templates. Browse to the location where you want to store your work. Use the View menu to display different windows, such as the Toolbox, Solution Explorer, Class View, Properties, and Dynamic Help windows.

C# Programming: From Problem Analysis to Program Design, 2nd ed.

8-6

Experiment with the pushpin icon on the title bar of specific windows. The Auto Hide feature minimizes that window.

Quick Quiz 1. Which template do you select for the project type if you plan to design an application that shows a windows form on the screen? Answer: Windows Application 2. The ________ icon can be used to minimize the window and place a tab for it in the current workspace. Answer: pushpin 3. True or False: Visual Studio will generate much of the code for you to create a Windows form. Answer: True 4. List three specific windows that can be opened in the workspace when a Windows application is being created. Answer: Class, Solutions Explorer, Dynamic Help

WINDOWS FORMS The top-level window for an application is called a “form”. There is an extensive collection of Control classes including a Form class, which is used as a container to hold other controls. Windows Form Properties The Properties window is used to view and change the design time properties and events of an object. In the Properties window, properties that have a plus symbol (+) to the left of the property name indicate that the property can be expanded. Groups of properties are collapsed together for easier navigation. Use intuitive names for most of the properties. Beginning with Visual Studio 2005, the IDE separates the source code into three files when you create a simple Windows application. Initially, these files are named Form1.cs, Form1.Designer.cs and Program.cs. The first two files, Form1.cs and Form1.Designer.cs, both include partial class definitions for the Form1 class. It is recommended that you never edit the Form1.Designer.cs file. You will normally only be editing the Form1.cs file. The Program.cs file contains the Main( ) method, where execution always begins. Inspecting the Code Generated by Visual Studio #region is one of the preprocessor directives used to mark sections of code that can be expanded or collapsed. Visual Studio adds a region labeled “Windows Form Designer generated code”. Clicking (+) expands the listing. There is also a #endregion.

C# Programming: From Problem Analysis to Program Design, 2nd ed.

8-7

Comparing the Code of Example 8-1 to Example 8-2 Visual Studio uses a method named InitializeComponent ( ) to build the form at run time. The call to this method is the only statement in the constructor. All code setting the properties that are set during design are placed in InitializeComponent ( ) method. Each of the properties are suffixed with the keyword this, referring to the current instance of a class. In the call to the Run ( ) method ( Application.Run(new Form1( )); ), no identifier is associated with the Form1 object. The new keyword creates an anonymous (unnamed) instance of Form1. The Form1 object identifier is not used anywhere else. Thus, there is no reason to name it. The Dispose ( ) is added by Visual Studio to perform memory management. The automatic garbage collector releases memory from the application after the program is halted. It cleans up or releases unused resources back to the operating system. Windows Form Events The topic of Chapter 9 is handling events. One way to add a method to handle events in Visual Studio is to find the event in the list of events (from the Properties window with the lightning bolt (Events) ) and double-click on the event name. Code is automatically added to the program. In the InitializeComponent ( ) method, the event is registered as being of interest using a statement similar to: this.FormClosing += new System.Windows.Forms.FormClosingEventHandler (this.Form1_FormClosing); The above statement registers the program to be notified when a user is closing the application. In addition, an event-handler method heading and an empty body is added to the code as shown here: private void Form1_FormClosing(object sender, FormClosingEventArgs e) { }

Quick Quiz 1. The top-level control onto which all others controls are added is called a _________ in a Windows application. Answer: form 2. True or False: When you are using Visual Studio to create a Windows application, you must type a using directive that reads using System.Windows.Forms;. Answer: False 3. True or False: Visual Studio inserts #region …#endregion preprocessor directive with a label of Windows Form Designer generated code. Answer: True 4. When does the Dispose( ) method do? Answer: It releases memory from the application after the program is halted.

C# Programming: From Problem Analysis to Program Design, 2nd ed.

8-8

CONTROLS System.Windows.Forms namespace includes controls with names such as Button, Label, TextBox, ComboBox, MainMenu, ListBox, CheckBox, RadioButton, and MonthCalendar. Each of these controls are classes with properties and methods. Each fires events—some of which you should write methods for—indicating what to do when its event is fired. A lot of code is added automatically for you when you place the control on the form. All of the control classes that can be added to a form are derived from the System.Windows.Forms.Control class, which means they inherit the characteristics of the Control class. Call attention to Figure 8-8 and 8-9. They show the controls that can be added. Place, Move, Resize, and Delete Control Objects Either double-click the control or drag and drop the control to the correct location on the form to place it. Resize controls using the standard Windows conventions of positioning the mouse pointer over the resizing handles. Clicking the Delete or Backspace key, once the control is selected, removes the control visually from the Form Designer view, but also removes all the constructor code and associated property changes relating to the selected object. With the release of Visual Studio 2005, the Windows Forms Designer has a SnapLine feature to help you accomplish precise layout of controls on your form. Horizontal and vertical line segments are dynamically created by the SnapLine feature to assist in the layout of controls. Options under the Format menu including Align, Make Same Size, Horizontal Spacing, and Vertical Spacing should be explored. After the controls are selected, use, for example, Align to align lefts, rights, or centers of controls. The Make Same Size selection is useful for sizing objects for consistency. Note that when you select more than one control to format, the last control selected is the one used as the template for the action. The Horizontal and Vertical Spacing options enable you to increase or decrease the amount of blank space displayed between objects. Methods and Properties of the Control Class Call attention to Table 8-2 for a list of Control properties inherited by control objects such as buttons and labels. Table 8-3 includes a list of the control methods. Some of the methods provide the same functionality as one or more of the properties. For example, the Show ( ) method functions the same way as setting the Visible property to true; Hide( ) does the same thing as setting the Visible property to false. Derived Classes of the System.Windows.Form.Control Class Figure 8-11 shows a visual representation of many of the controls you add to a form. They are labeled. • Label—used to provide descriptive text for another control. Can also be used to display information at run time. A number of properties can be set including Text, TextAlign, Visible, Font, and Location.

C# Programming: From Problem Analysis to Program Design, 2nd ed.





8-9

TextBox—used to enter data or display text during run time. Probably the most commonly used control because it can be used for both input and output. Text property is used to get or set the string value in the control. Other properties that are of interest include: MultiLine, ScrollBars, MaxLength, PasswordChar, and CharacterCasing. Table 8-6 describes these properties. Methods, including AppendText ( ), which adds text to the end of the current text of the TextBox and Clear( ), can be used with TextBox objects. Button—Objects that increase functionality. They enable a user to click a button to perform a specific task. When it is clicked by a user, the event-handler method is automatically called up—if the button has an event-handler method—and is registered as an event to which your program is planning to respond. Button objects have a number of properties, methods, and events. They also inherit the properties, methods, and events from the Control class. Specific properties and methods of interest include Enabled, Focused, Focus( ), AcceptButton, and Name.

TabIndex, inherited from Control, is useful for setting or getting the tab order of the controls on a form. By default, the tab order is the same order as the order of how the controls are added to the form. You can change this order when you are in View Tab Order by clicking the controls sequentially to establish the new order. Add a Click event to an object, such as a button, by double-clicking on the object in the Form Designer. When you add the event this way, the default event is registered and the method heading along with the empty body for the method is added. All that is required is for the programmer to write the program statements that should be executed when the event is fired. Another way to register an event is to select the event from the Properties window after clicking the Events icon.

Quick Quiz 1. True or False: Once controls, such as buttons or text boxes are added to a form, they can be resized, moved, or deleted using the standard Windows conventions. Answer: True 2. True or False: The Button class is derived from the Form class. Answer: False 3. The control that is probably used more often than other controls for both input and output is the ______. Answer: TextBox 4. The property that is used with most controls to set the caption for the control is the _______ property. Answer: Text

C# Programming: From Problem Analysis to Program Design, 2nd ed.

8-10

PROGRAMMING EXAMPLE: TempAgency Application This application is created to demonstrate the design and implementation of a graphical user interface for a Windows application. An application for a TempAgency is designed that accepts as input the contractor’s name, number of dependents, and the number of hours worked. It displays the gross pay, deductions, and the net pay for the worker. Two classes are constructed to separate the business logic from the presentation details. The Employee class defines a template for a typical payroll employee object. It includes the behaviors for determining withholding deductions and calculating the net take-home pay. The second-class instantiates objects of the .NET predefined Control classes (labels, text boxes, and button) and adds those objects to the Form object. Structured English (pseudocode) and class diagrams are included with the example. A prototype for the desired output is shown. Tables are shown documenting the properties that were set during design. The complete program listing is shown in the book and available as a Visual Studio project to demo for the class.

Discussion Questions Some interesting topics of discussion in this chapter include: • • •

Select a Windows application, such as a game or productivity package, and analyze the user interface in terms of the design considerations included in this chapter. Compare and contrast a typical Windows application to a console-based application. Why can a Windows application take twice as much time to develop as a console-based application?

Projects to Assign All of the Multiple Choice Exercises, Problems 1-20 Odd numbered Short Answer Exercises, Problems 21-25 Programming Exercises, Problems 3, 5, 9, and 10

Key Terms ¾ controls: objects that can display and respond to user interaction ¾ derived class: new class that that inherits the characteristics of the base class ¾ event: a notification from the operating system that an action, such as the user clicking the mouse or pressing a key, has occurred ¾ event handlers: methods that indicate what should be done when an event such as a mouse click on a button or the press of a key occurs ¾ graphical user interface (GUI): the menus, buttons, pictures, and text front end portion of the program ¾ Human-Computer Interaction (HCI): design and implementation of interactive computing systems for human use

C# Programming: From Problem Analysis to Program Design, 2nd ed.

8-11

¾ interface: the front end of a program—the visual image you see when you run a program ¾ preprocessor directive: directive indicating what should be done prior to processing the program statements ¾ Windows applications: applications that are usually graphical and that use the event model and receive messages from the operating system that an event has occurred