Overview
The first programs in this book are much like the programs in the early high−level languages, such as COBOL and FORTRAN. These programs work primarily on the command line and begin with straight−line logic. As you have progressed in your own programming, you have used more complex logical structures, such as loops and branching statements, and you have played around with more complex data structures, such as variables. The history of programming follows the same
progression. In the past two chapters, you looked at object−oriented programming, which
represents the current thinking in program design, but your programs still do not seem very modern because they are written on the ugly and unfriendly console. In the next few chapters, you will look at how C# is used in Windows programming. The programs you will write feature the capabilities of the Windows operating system, with all the graphical features you have come to expect from such a system.
Now you will explore how to build a program with a Windows interface. In this chapter you will Learn the basic concepts of a graphical user interface (GUI).
•
Use the IDE to build an interface.
•
Navigate the System.Drawing and System.Windows namespaces.
•
Add the most common GUI elements (text boxes, labels, images, scroll bars, and multiple selection elements) to your forms.
•
Write event−handling code.
•
Use event−driven programming.
•
Introducing the Visual Critter
As the final exercise for this chapter, you will build a critter program that has a graphical interface. This program will look and feel more like the programs you encounter on the Windows operating system. As usual, an image or two of the program is more helpful than just a description. Figure 6.1 demonstrates the Visual Critter in its default state.
Figure 6.1: This critter has a picture and some Windows−style controls.
You can see from Figure 6.1 that the newest version of the critter has much more visual appeal than the older versions. Modern users have become used to the convenience of a graphical interface, with all the various components such as text boxes, scroll bars, and command buttons. This version of the Visual Critter features several standard graphical controls.
Before diving into how all these controls work, you should play around with the program and see what it does. This is a highly interactive program, so you should open it from the CD−ROM and look at it live. I’ll show you a few of the highlights now in case you aren’t near a computer.
Figure 6.2: When the user clicks the image, the critter speaks.
I have attached code to the image so that when it is clicked, a message appears. The critter asks the user to change the critter’s name. Take a look at Figures 6.3 and 6.4 to see how the user can edit the name in the rectangle on the left side of the form.
Figure 6.4: After the user clicks the Change My Name button, the critter reports its new name. Any subsequent clicks on the critter will return the new name.
You can do other interesting things with the critter. You can change its mood by clicking the drop−down list of various temperaments. Figure 6.5 illustrates the critter after the user chooses a different mood.
Figure 6.5: When the user chooses a new mood from the drop−down list, the image changes accordingly.
The user can also change the critter’s size, by manipulating the scroll bar. Changing the location of the rectangle inside the elevator shaft changes the size of the critter image. Figures 6.6 and 6.7 illustrate this phenomenon.
Figure 6.7: When the user moves the scroll bar down, the critter grows.
You can also change the color of the background on which the critter resides. Illustrating these color changes on a black−and−white page is impossible, so you need to experiment with the program to see this phenomenon.
Creating a Windows−Style Program with a GUI
The Windows operating system, like most modern computer operating systems, provides a
graphical user interface (GUI). The GUI, pronounced “gooey,” (I love it when technical terms sound
silly) has several purposes. It is intended to make the user’s life easier. Manipulating a mouse and clicking screen elements is presumably easier than typing commands from a text−based menu. Visual elements on the screen are more aesthetically interesting than the kinds of programs you have seen so far in this book. Graphical elements, such as text boxes, list boxes, and scroll bars, also have practical benefits. Many of them are designed to limit user input. This prevents the user from entering invalid data and minimizes the error−checking code the programmer must write. Also, most graphical elements are already familiar to computer users. If you use only standard
components in your programs, most of your users will already know the basic operation of these objects. Finally, the visual components are predefined by the Windows operating system, so you don’t have to write all the code for them every time. All the visual elements are available as objects.
You can simply create an instance of the button object, for example, and you have a button. Most of the special visual objects you use to create Windows programs are housed in the
System.Windows.Forms namespace.
Thinking Like a GUI Programmer
Programs that feature a graphical user interface are different from console programs. The following sections explain these differences.
Objects Are Everywhere
The explosion in object−oriented programming happened at the same time that graphical user interfaces entered the mainstream. This is no coincidence. Graphical interfaces lend themselves beautifully to the object−oriented paradigm. The window itself is an object, as are all the various buttons and widgets on the screen.
The User Is in Control
In a console−based application, the programmer is king. You determine everything, and the program flows according to your whims. In short, the user can only respond to the program. In the graphical universe, the user is the king. Your program is set up as a playground for the user, and the programmer’s job is to anticipate the user’s actions. This makes GUI programs friendly (usually) for the user but more challenging for the programmer to write.
Programs Respond to Events
The entire design of a GUI program is different from one based on a console. Console−based programs generally have well−established beginnings, middle segments, and ending places, with one main loop. A GUI program is a much more fluid affair. You generally do not write a main loop at all! Instead, the nature of a Windows program implies a main loop that constantly repeats until the program is ended. This main loop patiently waits for the user to do something. The user’s action (such as pressing a button or moving the mouse) triggers an event. Most of the code in a GUI program comprises responses to events.
Problems Are Solved Differently
In the console world, you have to build everything, and your program follows a logical flow. You can design a flowchart and expect the code to follow a similar structure. In a GUI program, the
problem−solving process is more visual. You often begin by sketching out a screen. Then you figure out which controls and objects will bring that screen to life. Most of your code has to do with
choosing objects, manipulating the properties of those objects, and then responding to events that occur when the user interacts with these objects.
Events Are Added to the Object Model
GUI programming requires that you expand your thinking about objects. You are already
accustomed to objects’ having properties and methods, but user interface objects (as well as other kinds of objects) also require a special characteristic called an event. If a property is an adjective (it describes a characteristic of an object) and a method is a verb (it describes what an object can do), an event is an interjection, such as “Ouch!” or “Help!” Events are messages sent to other objects in the system. Normally, you use an event to indicate that something has happened—the user has clicked a button or moved a scroll bar, for example. Other events can be automatically triggered by
the operating system or the passage of time.
Creating a Graphical User Interface (GUI)
To learn the basic concepts of designing GUI forms, you’ll re−create the classic Hello World
program from Chapter 1, “Basic Input and Output: A Mini Adventure.” This time, you will write it as a Windows GUI program. Although creating a graphical interface is more challenging than designing a console application, the Visual Studio IDE provides features that greatly simplify the process.
Creating a Windows Project
To begin, you create a C# program as usual. When you are asked for the type of project, choose Windows Form from the templates list box (see Figure 6.8).
Figure 6.8: You can choose to make a Windows project when you start a new C# project.
The editor will continue to load as usual, but the screen will be a little different from what you are used to.
Trap Be sure to choose a good name when you are creating the project because it is very difficult
to change later. Leaving the name “WindowsFormApplication1” then changing it to
“GlitterCritterLiveInVegas” requires several painful steps that can cause the program to not compile.
Using the Form Builder
The IDE has a new feature when you are building a Windows−style project. Figure 6.9 shows a graphical editor with a form in place. The visual form designer contains a number of panels and features to simplify the creation of GUI interfaces:
Figure 6.9: When you build a Windows project, the IDE changes to add graphical features.
Toolbox. Features components you can place on your form. You can highlight any object
and draw it onto the form, as in an image−editing program.
•
Form. Another page in the main area where the code, object browser, and help screens
have appeared before. You can resize the form by dragging on the small squares around its edges.
•
Properties window. Displays all the properties of the currently selected object. In this case,
it shows all the properties of the form object that makes up the program. You can dynamically change a visual object’s properties by manipulating the Properties window.
•
Properties tab. Used to select the Properties window from the many windows available in
this pane.
•
Sort Properties Alphabetically. Alphabetizes all the properties in the Properties window by
property name. This can be useful when you know the exact name of the property you want to change.
•
Sort Properties by Category. Displays the properties by category. For example, all the
properties dealing with the object’s appearance are grouped together, as well as the properties dealing with the object’s behavior. I have found the categories to be unintuitive (what’s the difference between appearance, design, and layout properties, for example?) However, when you become familiar with the way properties are organized, this is an easy method to find what you need.
•
Trap Sometimes, one of the windows (especially the Properties window) “disappears” while you
are working. The highly flexible design of the .NET IDE can make the exact locations of various elements hard to predict. If you need access to a window and cannot see it on the screen, you can always select it from the View menu. In particular, when the Properties window is missing, you can find it by clicking the tabs in the right column of the editor.
Changing the Form’s Properties
If the form is highlighted (the sizing squares around its perimeter are visible), you can change its properties in the Properties window. Examine the form’s title bar. When you begin, the title bar reads Form 1. This becomes the title bar of your finished program. The title bar usually contains the
name of the program and sometimes other information. In any case, the form’s title bar is related to the form’s text property. Most visual objects have a text property, which allows you to change text on the object. Find the text property in the Properties window, and type Hello World!! in the box.
Trick The Properties window is a very important part of visual programming, so here are a few tips
for using it. I like to make it larger than the default size. You can resize it by dragging its borders. You can also scroll up and down in the window if there are more properties than you can see at one time on the screen. You can display the properties alphabetically by choosing the button that has “AZ” on it at the top of the Properties window, or you can sort by category, by choosing the icon immediately to the left of the “AZ” icon.
For now, simply change the form’s text property. If you like, you can play around with other properties, too. Try to change the background color of the form. Experiment!
Trap Because of a flaw in the IDE design, the program will not run properly if you change
the name of your startup form. In the next section you will learn how to fix this problem, but for now, just leave the form’s name as Form1.
Adding a Label to the Form
Although you have changed the form’s text to Hello World!!, the greeting is too subtle for most users to notice. Larger text centered in the middle of the screen would be better. This is easy to do. Look at the Toolbox, which should be on the left side of the screen. If it is not visible, select it from the View menu. The Toolbox contains visual objects you can place on your forms. These special
objects are sometimes called controls or components. You select the component by clicking it in the Toolbox and then draw the component onto your form. It works much like a painting program, except that rather than paint colors on a palette, you paint controls onto a form.
Hint Like the other windows in the .NET IDE, the Toolbox has several faces. If you don’t see the
controls you are looking for, make sure that you have selected the Windows Forms tab in the Toolbox. Also, the number of controls available can exceed the space allocated for the Toolbox. You use the up and down arrows on the Toolbox window to scroll through the controls available to you.
After a control is placed on the form, you move it by dragging it around. You resize it by manipulating the sizing rectangles on the sides and corners of the control.
Changing the Label’s Properties
Like any other controls, the label supports intriguing properties. The label’s text property determines what text will be placed in the label. Figure 6.10 shows the changes I made to the label—see whether you can match my changes. I modified the font name, font size, TextAlign, and BackColor properties to get the effect I was looking for. Of course, you can modify the program however you like.
Figure 6.10: The program says a Windows−style hi, without a line of code!
Running the Program
The .NET editor makes creating a simple GUI program very easy. When you click the Run icon, you see the working version of your program. Figure 6.10 features my version.
This program looks good and is very easy to write. You don’t add a single line of code. However, the program is based on code, so you need to understand how the code is built behind the scenes. Sometimes you will want to write code without the graphical editor You will learn how to do this in Chapter 8 “Arrays: The Soccer Game.” More often, you will find that the editor makes a mistake you must correct. Of course usually you will add more code so that your program does something. Looking at the code generated by the editor makes sense.
Examining the Code of a Windows Program
When you create a new Windows application, the editor shows you a graphical representation of the form, not the form itself. This graphical window is called the Visual Designer. Your program is still based on code. The Designer view simply gives you an alternative way of viewing and modifying the code. To see the underlying code, choose Code Window from the View menu. Figure 6.11 shows the editor displaying the code for the Hello GUI.
Figure 6.11: This code creates the Hello GUI program.
As you scroll through the code, you see that the editor wrote a lot of code. Although the editor writes this automatically, it is not perfect. I’ll show you the automatically generated code and explain what it is doing.
Adding New Namespaces
When you create a console program, the editor presumes that you will want access to the System namespace. In a Windows program, you need access to other namespaces as well. All the visual components are objects, and most of them live in the System.Windows.Forms namespace. Additionally, all the objects used to position controls on a form belong in another important namespace, System.Drawing. When you create a Windows program, the C# editor automatically attaches references to these two critical namespaces, and a few others as well:
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data;
For this simple program, you need not worry about the other namespaces, but it doesn’t hurt to leave them in.
The System.Windows.Forms Namespace
Most of the controls visible on the toolbar are housed in an important namespace,
System.Windows.Forms. If you include access to this namespace, your programs can use forms and all the other controls on the Toolbox. Not surprisingly, nearly every Windows−based program uses this namespace. Peruse the object browser or documentation to see all that this namespace has to offer. Be warned, though. The namespace is huge, and you don’t need to memorize all the