Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Microsoft CSharp Programming For The Absolute Beginner (2002) [eng]-1.pdf
Скачиваний:
46
Добавлен:
16.08.2013
Размер:
15.71 Mб
Скачать

picture box is a tall skinny rectangle, the image will appear to be taller and skinnier than usual. The Center setting causes the image to be displayed at its default size but centered within the image box, with the edges cropped out. The AutoSize setting causes the picture box to shrink or grow so that it is exactly the right size for the image.

Adding a Scroll Bar

Scroll bars are a wonderful innovation in interface design. Many times, you need some sort of integer input. If you ask a user to type in a number, you never know exactly what you will get. You usually have to do all sorts of error−detection gymnastics to ensure that the number is properly formatted and is not written out. Also, users generally prefer to use some sort of visual interface if they are in a GUI. The scroll bar control is designed to let the user visually enter a number. Much of the time, the user isn’t even aware that this is what he or she is doing, but that’s what scroll bars are for. The .NET framework supplies two scroll bar controls, but they are almost identical. The HScrollbar is aligned horizontally, and the VScrollbar is vertical. (Not surprisingly, both are inherited from a generic Scrollbar class.) The little box inside the scroll bar is sometimes called the elevator. The Value property of a scroll bar is an integer related to the position of the elevator. For horizontal scroll bars, smaller values are on the left. For vertical scroll bars, smaller values are at the top. You can set a range of values your scroll bar will return, with the Maximum and Minimum properties. Also, you can change how much the elevator moves when the user clicks the arrowheads, by setting the SmallChange property. You can indicate how far the elevator moves when the user clicks the shaft, by adjusting the LargeChange property. For the Sizer program, I chose a horizontal scroll bar with values between 50 and 200 because I want the image to vary between 50x50 and 200x200. I set the Minimum property to 50 and the Maximum property to 200. I left everything else alone.

Writing the Event−Handling Code

This program requires only one line of custom code, and that goes in the default event handler of the scroll bar. When the scroll bar is changed, the picture box’s size should also change to have the same height and width as the scroll bar’s value. Here’s the event code:

private void scrSize_Scroll(object sender, System.Windows.Forms.ScrollEventArgs e) {

picCritter.Size = new Size(scrSize.Value, scrSize.Value);

}

The Scroll event occurs whenever the user moves the scroll bar. When this happens, the program changes the Size of picCritter. The Size property requires a size object (I learned that by looking at the object browser for the picture box). I looked up the size object and found that I could create it with two integers. Because I wanted the picture box to remain square, I just set the value of the scroll bar as both the X and Y values for the new size object.

Revisiting the Visual Critter

The Visual Critter program mentioned at the beginning of this chapter combines all the techniques you’ve learned throughout the chapter—and adds a few minor twists. The visual Critter is a picture box. The user changes the visual critter’s characteristics by manipulating the various controls on the screen.

161

Designing the Program

As a starting point, look at the sketch I used to design the program in Figure 6.24.

Figure 6.24: This sketch helped me to define how my program would be built.

Because the visual interface is so critical to GUI programs, the statement of the problem almost always involves at least one sketch of the user interface. (If you prefer not to sketch, your notes can be in English.) In visual programs, it’s a very good idea to figure out how the screen layout will be designed and determine the main types of objects you expect on the screen. In this type of sketch, I also like to name all my objects and write down any special characteristics of the objects. For example, you can see that I have predicted the range of the scroll bar and have indicated that several of the picture boxes will be invisible. The point of the sketch is not to solve all the programming problems. The goal is to make sure that you know what you’re trying to accomplish before you start writing code. Changing your ideas on paper is much easier than making changes after you start writing the program.

From the sketch, you can see that the program is centered around a picture box named picCritter. All the other elements on the form modify picCritter. I have decided to let the user change picCritter in four ways: The user can change the critter’s mood (which will change the image shown in picCritter) with a special form of the list box called the drop−down list box. The user can change the critter’s name by typing in a text box and clicking a button. The critter’s color can be modified by selecting a new color from a set of radio buttons, and the size is changed through a scroll bar. While I was sketching this out, it became clear that the number of controls on the form would be overwhelming, so I drew boxes around various elements to group the similar controls. For example, all the radio buttons are in a box, as are the text box and command button that deal with the critter’s name. I also added three special picture boxes that will be invisible to the user. I’ll explain soon what those are used for.

In the Real World

Many programmers design their programs first on chalkboards or whiteboards because these surfaces allow for even more flexibility than paper. A surprising number of my programs have been designed on napkins because a good idea came to me while I was at a restaurant. It doesn’t matter how you write your sketch (until you become a professional, when there will undoubtedly be standards), but you should do your initial work away from the programming environment. Resist the

162

temptation to design your form on−the−fly in the Designer. The .NET Designer will become confused if you change the design and layout too many times. It’s better to start the editor when you are clear about what you want your program to do.

Determining the Necessary Tools

Almost all the tools necessary for this project are described throughout this chapter, but my sketch pointed out the need for a couple variations.

A list box is a nice control but takes up a lot of room on the screen. What works better is the combo box, which is a form of the list box that expands when needed but takes up less room on the screen when the user is not using it. The combo box is a souped−up list box. It has all the same features as the traditional list box. Also, it can be set up so that the user can type in a value or set up as a list box with drop−down behavior. You set this behavior by modifying the comboBoxStyle property. A drop−down list box will be a nice addition to the program because it allows the user to pick from several options but doesn’t take up too much room on the screen.

In the Real World

Drop−down list boxes are popular with programmers because they allow many choices without taking as much space on the screen as check boxes, radio buttons, or traditional list boxes. Space is crucial when more items might be added to the list of choices. The other types of controls require space for new options. With a drop−down list, you can always add more elements to the list without requiring any more screen real estate. The other style of combo box is handy when you want to let the user type in a value or choose from a list.

The form has many controls on it, so breaking up the form into smaller segments is necessary. By digging around in the Toolbox, I found the panel control, which is perfect for this kind of thing.

I also needed to store the various images for the critter temporarily. I simply created extra picture boxes and set the visible property to false. The picture boxes are then invisible, but you can still copy the image property over to change the image of the picCritter picture box.

Designing the Form

After I figured out how the project should be laid out, I built the form. Figure 6.25 shows the form as it is being built in the Designer.

163

Figure 6.25: The form is easy to build if you have a sketch to follow.

I built the form by following the sketch. Notice that I added some panels to group the various types of controls and added a few labels to help the user understand what’s going on. I changed the panel’s border property to get the 3−D effect.

Trick When you use panels to separate controls, be sure to draw the panel first and then draw the control inside the panel. If you draw the control first, it will be attached to the form itself, rather than to the panel. If you draw the control inside the panel, you can move the panel, and all the controls will move with it. Also, you can use panels to isolate groups of radio buttons if you have more than one group of such controls on your form.

I also added one label above the critter image to handle displaying the critter’s name. In the original plan, I didn’t have a way for the critter to tell its name.

Writing the Code

In this type of program, most of your code consists of anticipating user actions and writing methods to handle events. All the events are the default events of the objects.

Adding Instance Variables

The Visual Critter program requires only one additional instance variable. I added myName as a string variable to hold the critter’s name. As usual, the instance variable goes inside the class definition line and before any method definitions.

Responding to a Change in the Combo Box

The combo box cboMood will fire off a SelectedIndexChanged event whenever the user chooses a new element from the combo box. If that happens, the program copies an image from one of the hidden image boxes.

164

private void cboMood_SelectedIndexChanged(object sender, System.EventArgs e) {

switch (cboMood.Text){ case "happy":

picCritter.Image = picHappy.Image; break;

case "indifferent":

picCritter.Image = picIndiff.Image; break;

case "mad":

picCritter.Image = picMad.Image; break;

default:

picCritter.Image = picIndiff.Image; break;

} // end switch

}// end cboMood event

The Text property of cboMood will contain whatever value is selected in the combo box. A switch statement examines all the possible values and copies the Image property of the appropriate invisible picture box to the image.

In the Real World

You can select and store images in several ways, but this is one of the simplest. Having the images already loaded in memory in hidden controls is preferable because loading an image from the disk drive can be a slow process. If the image is already in the computer’s memory (as it is when assigned to an invisible picture box), the image can be copied very quickly to the visible picture box.

Notice that I added a default clause, even though it should never happen. You should add a default clause to every switch statement because strange things happen and it’s better to be safe than sorry.

Clicking the Critter

When the user clicks the critter, it should say something. Here’s the code that occurs when the user clicks picCritter:

private void picCritter_Click(object sender, System.EventArgs e) {

if (myName == ""){

lblName.Text = "Please give me a name!";

}else {

lblName.Text = "My name is " + myName + "!"; MessageBox.Show("Hi, my name is " + myName);

}// end if

}// end picCritter click

If the myName variable hasn’t been changed by typing a new name in the text box, the critter asks the user to supply a name. Otherwise, the program copies a friendly message to the lblName label. Notice the line that starts with MessageBox. The message box object is a convenient way to send a quick message to the user. Use the MessageBox.Show() method to say something in a little dialog box.

165

Trap The MessageBox.Show() method is very handy but interferes with the flow of the program. Also, if you use it too much, your users will be annoyed. Integrating all your output into the form (when you can) is much more in the spirit of GUI programming. Also, if you’re familiar with programming in Visual Basic or JavaScript, you might wonder where the equivalent to inputbox or prompt is in C#. The .NET framework does not supply a quick dialog for input.

You have to make your own if you want one. Generally, though, you can get all the input you need from your programs.

Changing the Critter’s Name

The txtName text box and the btnName command button work together to let the user change the critter’s name. You might be surprised that no code is attached to the text box. All the code for name changing happens in the command button. Here is the code:

private void btnName_Click(object sender, System.EventArgs e) {

if (txtName.Text == ""){ MessageBox.Show

("Please enter a name in the text box and click the button again");

}else {

myName = txtName.Text;

MessageBox.Show("OK, You changed my name.");

}// end if

}// end btnName click

This method ensures that there is a name in the text box. Then it copies that name to the myName variable and lets the user know that the name has been changed.

Changing the Critter’s Color

The critter’s color is changed through the radio buttons. The code is very straightforward:

private void radRed_CheckedChanged(object sender, System.EventArgs e) {

picCritter.BackColor = Color.Red; } // end radRed event

private void radGreen_CheckedChanged(object sender, System.EventArgs e) {

picCritter.BackColor = Color.Green; } // end radGreen event

private void radBlue_CheckedChanged(object sender, System.EventArgs e) {

picCritter.BackColor = Color.Blue; } // end radBlue event

Each of the radio buttons immediately changes the background color of picCritter to the appropriate color. Notice that all the legal color values are available in the System.Drawing namespace. If you type Color. while this namespace is available, you see a complete list of color names you can use.

Changing the Critter’s Size

The Critter’s size is changed by a scroll bar. In fact, I stole the code directly from the Sizer program featured earlier in this chapter.

166

Соседние файлы в предмете Программирование на C++