Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Beginning Visual Basic 2005 Express Edition - From Novice To Professional (2006)

.pdf
Скачиваний:
386
Добавлен:
17.08.2013
Размер:
21.25 Mб
Скачать

220

C H A P T E R 8 B U I L D I N G W I N D O W S A P P L I C A T I O N S

FEELING LAZY?

There’s nothing wrong with being a lazy programmer. Lazy programmers tend to find the best, most efficient ways of doing things simply because they are too lazy to do things the laborious way.

So if you’re feeling lazy, try holding down the Ctrl key on your keyboard and then clicking each radio button on the form. You’ll find that you can select them all at once this way. You can also then set all the radio button event handlers in one fell swoop, rather than clicking through by hand.

See, it pays to be lazy sometimes.

Click the first radio button, and then using the Properties window, click the lightning bolt to see the list of events for the control. Click in the entry area next to the CheckedChanged property, just once. In other examples, you would have double-clicked this to automatically drop into the code window with an event handler created and named for you by VB 2005 Express. This time around, you’re going to give the event handler your own name.

Type in TicketTypeChanged.

When you press the Enter key, the code editor will open. As you’ve probably guessed from the name, this event fires whenever the Checked property of a radio button changes. The important thing to note is that this event fires both when a radio button is selected and when it’s deselected—it’s not like a Click event on a button, which would fire only when the user explicitly pointed at the control with the mouse and clicked it.

Now, don’t bother writing any code into the event handler just yet. Instead, head on back to the designer view and select the next radio button. This time, in the event list click the drop-down arrow beside the CheckedChanged event and select the event handler you just created. Repeat the process for the remaining radio buttons on the form and you’ll end up with them all having the same event handler for their CheckedChanged event.

When you’ve set the radio buttons all up, press F7 to drop into the code window once again.

Take a look at the event handler method you created:

Private Sub TicketTypeChanged(ByVal sender As System.Object, _ ByVal e As System.EventArgs) _

Handles economyRadio.CheckedChanged, upperRadio.CheckedChanged, _ premiumRadio.CheckedChanged, firstRadio.CheckedChanged, _ businessRadio.CheckedChanged

End Sub

C H A P T E R 8 B U I L D I N G W I N D O W S A P P L I C A T I O N S

221

Notice that you get two parameters passed to the event. The first one is really useful because it is the control that fired the event. You can use this to figure out just why the event fired (was the control deselected or selected). More to the point, you can pull the text out of the control’s Text property and use that to set up your ticketClass member variable.

Add code that looks like this to the event handler:

Private Sub TicketTypeChanged(ByVal sender As System.Object, _ ByVal e As System.EventArgs) _

Handles economyRadio.CheckedChanged, upperRadio.CheckedChanged, _ premiumRadio.CheckedChanged, firstRadio.CheckedChanged, _ businessRadio.CheckedChanged

Dim ticketTypeButton As RadioButton = CType(sender, RadioButton) If ticketTypeButton.Checked Then

ticketClass = ticketTypeButton.Text End If

End Sub

The first thing this new code does is cast the sender parameter to a RadioButton; you know that it will work because this code gets called only in response to a RadioButton on the form calling it.

After that’s done, you can just take a look at the Checked property to see if the event fired because the sender control got selected. If it did, the contents of its Text property are copied into your member variable.

Run the program now and you’ll find that it works just as it did a short while ago. The difference, of course, is that now it’s a lot smaller and much more readable.

Date Pickers

If you want to work with dates in your user interface, there are two controls that you are going to have to get to grips with: the DateTimePicker control and the MonthCalendar control. Deep down, you need to learn only the MonthCalendar control, because the DateTimePicker is really a text box with a MonthCalendar attached to it. Therefore, we’ll focus on the MonthCalendar control here.

The MonthCalendar control is fantastic. You just drag it onto a form in your application and instantly you have a graphical calendar display, as you can see in Figure 8-27.

222

C H A P T E R 8 B U I L D I N G W I N D O W S A P P L I C A T I O N S

Figure 8-27. The MonthCalendar control provides an interactive graphical calendar view.

If you resize the MonthCalendar control, then rather than stretching the month view, you actually get to see more months, as you’ll see shortly in the next “Try It Out.”

In terms of formatting, the MonthCalendar control has an extensive set of properties to let you completely customize the way the control works. You can change the colors of the title bar on the control with the TitleBackColor and TitleForeColor properties, and change the colors within the calendar view itself with the standard ForeColor and BackColor properties. Aside from the cosmetics, you can also change how the calendar displays dates by using the properties shown in Table 8-4.

Table 8-4. The Most Common Properties of the MonthCalendar Control

Property

Description

ShowToday

Set to True, and the calendar control will display today’s date right at

 

the bottom of the calendar itself.

ShowTodayCircle

Set to True, and today’s date will also be circled in red within the

 

calendar.

FirstDayOfWeek

This is an enum and can be set to Monday, Tuesday, and so on, to set

 

which day of the week appears as the first day of the week in the

 

calendar view.

MaxDate, MinDate

The maximum and minimum dates that the MonthCalendar control

 

will allow the user to move to.

SelectionRange.Start, Sets up two dates, and the MonthCalendar control then selects all

SelectionRange.End

dates between and including those dates.

BoldedDates,

These properties both take arrays of DateTime objects and set those

AnnualBoldedDates

dates to bold. The AnnualBoldedDates array bolds the dates passed in

 

as you scroll from year to year.

 

 

C H A P T E R 8 B U I L D I N G W I N D O W S A P P L I C A T I O N S

223

In terms of events, the MonthCalendar control raises all the usual ones (Click, LostFocus, GotFocus, and so on), but also exposes two just for working with dates: DateSelected and DateChanged.

The DateChanged event fires whenever the selected date changes, either by virtue of program code changing it, or the user clicking on a date in the calendar. The DateSelected event, on the other hand, fires only when the user clicks on a date with the mouse.

The DateTimePicker is a much simpler control. In fact, you work with it pretty much like a text box; it’s just that at runtime the user gets a drop-down arrow to click on for displaying the calendar, as in Figure 8-28.

Figure 8-28. The DateTimePicker works just like a text box, but with a down arrow to display and choose from a calendar view.

You get at the date selected from the calendar through the control’s Text property, just as with a text box. Also, you can enter data directly into the text box part of the control and it will automatically check whether the data entered is a date, and then highlight the appropriate date in the drop-down calendar. Additionally, the control does still expose the formatting properties I mentioned earlier to format the view of the drop-down calendar itself.

Anyway, let’s take a look at these two controls in a “Try It Out.”

Try It Out: Working with the DateTimePicker and MonthCalendar

Start up a new Windows application project and drop a Label, DateTimePicker, Button, and MonthCalendar control onto the form, as in Figure 8-29.

224

C H A P T E R 8 B U I L D I N G W I N D O W S A P P L I C A T I O N S

Figure 8-29. Arrange your controls like this. The MonthCalendar control will initially show just one month, until you resize it to show more.

What you are going to do with this application is select dates from the picker and display them in bold in the calendar view. Conversely, when the user clicks on a date in the calendar view, you’ll have that date shown in the picker automatically.

As usual, to ensure that your code looks the same as mine, you’ll need to set the Name properties for the controls. Set the name of the button to addButton, the DateTimePicker to specialDate, and the MonthCalendar to calendar.

Let’s write the code first to move a date chosen in the MonthCalendar view into the DateTimePicker. Select the MonthCalendar and then click the lightning bolt at the top of the Properties window to show the events that the control supports. Find the DateSelected event and double-click it to drop into the code editor, ready to write the event handler.

C H A P T E R 8 B U I L D I N G W I N D O W S A P P L I C A T I O N S

225

When the user chooses a date in the MonthCalendar view, the event that’s raised gets passed a DateRangeEventArgs object called e. This contains two useful properties: Start and End. These are used when the user selects a range of dates. We’re only interested in one though, so you can just use

e.Start

in your code to get at the date chosen. The problem is that the value Start holds a DateTime value, while you are going to need a string to set the text property of the DateTimePicker. So, you’ll need to call ToLongDateString() on the Start value to convert the selected date into a string. Confused? It’s actually simple. Go ahead and add code to the event handler so that it looks like the following code:

Private Sub calendar_DateSelected(ByVal sender As System.Object, _ ByVal e As System.Windows.Forms.DateRangeEventArgs) _ Handles calendar.DateSelected

specialDate.Text = e.Start.ToLongDateString()

End Sub

As you can see, you get Start from the DateRangeEventArgs object, and call ToLongDateString() on it to convert the selected date into text. The result is stored straight into your DateTimePicker control’s Text property.

Now to set up the other half of the story. When the user selects a date from the DateTimePicker control, you want the date to show up in bold in the MonthCalendar control. The MonthCalendar control has a property called BoldedDates, which is an array of DateTime objects. What you need to do is grab that array and add a new element to it. You can do this quite easily because Visual Basic lets you change the size of an array with a call to Redim Preserve. Double-click the Add button to drop into the code editor and then add the following code:

Private Sub addButton_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles addButton.Click

Dim boldDates() As System.DateTime boldDates = calendar.BoldedDates

ReDim Preserve boldDates(calendar.BoldedDates.Length + 1)

boldDates(calendar.BoldedDates.Length + 1) = _ System.DateTime.Parse(specialDate.Text)

calendar.BoldedDates = boldDates

End Sub

226

C H A P T E R 8 B U I L D I N G W I N D O W S A P P L I C A T I O N S

Let’s walk through what this does. First, you create an array of DateTime objects. Because you don’t know how big this array needs to be, no size is specified inside the parentheses.

Next, you copy the BoldedDates array from your calendar control into the new array. In order to add a new bolded date, you now need to resize the array. This is done by calling Redim Preserve. It actually uses the same format to resize an array as delcaring it. You specify the name of the array, its size, and its type. For the size, you just grab the length of BoldedDates and add 1 to it.

Next, you copy the date the user selected from the drop-down into the last element in your array. To do this, though, you need to ask the DateTime data type to parse the text the user selected into the right format.

Finally, you copy your new array, complete with new date, back into the BoldedDates property on the calendar.

Run the program now. Click a date in the MonthCalendar view to see it in the DateTimePicker. Then choose a new date in the DateTimePicker and click the Add button to see that date appear in bold in the MonthCalendar.

Summary

You covered a lot of ground in this chapter, looking at the most common properties and events of all controls, as well as drilling down into event handling. You also took a look at some of the most common controls you’ll use in your apps, including buttons, text boxes, date and time controls, radio buttons, and check boxes. In fact, armed with your knowledge of Visual Basic 2005 Express, you could probably go some way now to developing a simple Windows application on your own.

The journey, though, is far from over. In the next chapter you’ll take a look behind the scenes at event handling and I’ll equip you for the more complex controls and chapters to come.

C H A P T E R 9

■ ■ ■

Windows and Dialogs

In the preceding chapter you covered much of the basics behind building a user interface. You took a look at building a user interface by dropping controls onto a form, and also the common events and properties associated with those controls. Of course, you also took a look beneath the covers at the sort of code you’ll need to write to breathe life into your glorious user interfaces.

One element, though, was conspicuous by its absence: the window itself. Nearly all applications you use on a daily basis consist of more than one window. Many will pop open dialog boxes to prompt you for information when you want to load or save a document. Others may have a user interface that consists of many windows. In fact, a great many Microsoft Windows applications even seem to have special code in them that can spot when things happen to the windows themselves, confirming whether you really want to quit, for example, when you click the Close button on a window and things like that.

So, that’s the focus of this chapter. You’ll learn pretty much everything you’ll ever need to know to work with windows and dialogs in an application. You’ll see how to open, close, and hide windows in code, how to change the visual style of a window, and even how to put a window inside another window. You’ll also explore just how to use and develop dialogs for your applications, and I’ll talk you through how to harness the power of Windows’ built-in dialogs (the Open, Save, and Print dialogs, for example).

Windows (or Forms)

You probably have noticed by now that I tend to use the word “form” a lot when what I actually seem to mean is “window.” It’s a hangover from the old days of Visual Basic that just stuck around in the .NET world. The thing that you drop controls onto in the visual designer part of Visual Studio 2005 is a form. At runtime it’s a window. Ultimately though, we’re talking about exactly the same thing but in different environments: the designer and at runtime.

227

228 C H A P T E R 9 W I N D O W S A N D D I A L O G S

You’ve worked through a few examples now of adding controls to windows to build up user interfaces, and it’s easy to fall into the trap of thinking that the window or form is really just some dumb container thing that you draw on at design time. There’s a lot more to it than that, though. You see, understanding the form, its properties, events, and methods is key to bringing multiple windows, dialogs, and container windows into your applications. In fact, when you take a look at the “Common Dialogs” section, you’ll see that Windows itself provides some pretty complex ready-made forms for you to just pick up and go.

Let’s start off with the basics.

The Main Window and How to Change It

You’ve probably noticed by now that when you start a Windows Forms project in Visual Basic 2005 Express, you start with a project that contains a single form. When you run the program in the editor, the window appears, and when you close the window, the application stops running. How come?

In Chapter 8 I gave a quick introduction to how Windows programs work beneath the covers, particularly the event-handling system. If you write a Windows application the old-fashioned way using C or C++, the entire program is controlled by a single loop that watches for new event messages to appear. The loop grabs the message and forwards it onto the window concerned, and you then need to have some fairly nasty-looking code in place to respond to all the different kinds of event messages that you expect the window and its controls to respond to. It’s a project setting that controls just which window gets loaded at runtime, and thus which window is the first to receive messages.

PEEKING INSIDE .NET

Passionate programmers, ones who really love to write code and try things out, typically destroyed all their toys as children. We like to know how things work, and invariably enjoyed pulling things apart to see, much to the chagrin of our parents.

You can do the same with .NET, but without the heartache of it ceasing to work after you do. When you hit F5 or click the Run button on the toolbar, the VB compiler comes to life, turning your lines of code into something called Microsoft Intermediate Language (MSIL). The .NET runtime then looks at this MSIL and turns it into something the computer can actually work with in order to run the program.

There is a great tool out there called Reflector, from a guy named Lutz Roeder, that can do the reverse, turning MSIL into C# or even Visual Basic 2005 code. If you want to take a look at exactly what Application.Run() really does behind the scenes, download Reflector (http://www.aisto.com/ roeder/dotnet/), load up your program, and take a look. This is a great way to take a peek at the inner workings of .NET itself, and of course to learn programming techniques from the talented people at Microsoft.

C H A P T E R 9 W I N D O W S A N D D I A L O G S

229

When you first create a Windows project in Visual Basic 2005 Express, you’ll notice in the Solution Explorer a strange item called simply MyProject. Double-clicking this opens up the project properties window, which you can see in Figure 9-1.

Notice the third text box down on the left: Startup Form. If you have more than one form in the project and want a different one to appear (perhaps a form designed as a splash screen welcoming users to your application), all you need to do is select the new form from the drop-down and close the properties page.

Figure 9-1. The project properties govern which form starts when you run the program, among other things.

Opening and Closing Windows

A Form (System.Windows.Forms.Form) is a class. All you need to do to display it is instantiate the class as an object and call the Show() method. What could be easier? Similarly, to close a window, just call the Close() method.