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

Beginning Visual Basic 2005 (2006)

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

Chapter 6

8.Now select tbrUpperCase in the Class Name combo box and the Click event in the Method Name combo box. Add the following highlighted code to the Click event handler:

Private Sub tbrUpperCase_Click(ByVal sender As Object, _

ByVal e As System.EventArgs) Handles tbrUpperCase.Click

‘Make the text uppercase

UppercaseText()

End Sub

9.Now add the following procedure to change the text to all lowercase:

Public Sub LowercaseText()

‘Make the text lowercase

EditText = EditText.ToLower

‘Update the status bar text

StatusText = “The text is all lowercase” End Sub

10.Now select tbrLowerCase in the Class Name combo box and the Click event in the Method Name combo box. Add the following code to the Click event handler:

Private Sub tbrLowerCase_Click(ByVal sender As Object, _

ByVal e As System.EventArgs) Handles tbrLowerCase.Click

‘Make the text lowercase

LowercaseText()

End Sub

11.Run the project and enter some text into the box in a mixture of lowercase and uppercase. Then click the Uppercase button to make the text all uppercase as shown in Figure 6-14. Clicking the Lowercase button will convert the text to all lowercase, and clicking on the Red or Blue buttons will cause the text to change color. Finally, clicking the Clear button will cause all text to be cleared and the color and case to be restored to the default.

Figure 6-14

196

Building Windows Applications

How It Works

This Try It Out was really quite simple. By this time, you are quite adept at creating the Click event handler for buttons on your form, and creating the Click event handler for a toolbar button is no different. The first thing that you did was to create the Click event handler for the Clear toolbar button and add the code to call the ClearEditBox procedure:

Private Sub tbrClear_Click(ByVal sender As Object, _

ByVal e As System.EventArgs) Handles tbrClear.Click

‘Clear the edit box ClearEditBox()

End Sub

Next, you created the RedText procedure to change the text in the edit box to red and to update the status bar with the appropriate information. To change the color of the text in the edit box, you set the ForeColor property of the edit box using the Red constant from the Color enumeration. (The Color enumeration contains an extensive list of named colors.) The ForeColor property remains red until you set it to something else — so clicking the Clear button turns it back to black:

Public Sub RedText() ‘Make the text red

txtEdit.ForeColor = Color.Red

‘Update the status bar text StatusText = “The text is red”

End Sub

You also change the text in the status bar using the StatusText property to display a message indicating the text color has changed. As soon as you start typing again, the message in the status bar is changed to “Ready”, as set by the TextChanged event handler for the edit box.

In order to call the RedText procedure you added code to the Click event for the Red button on the toolbar:

‘Make the text red

RedText()

The code for the Blue button on the toolbar works in the same manner. You created the BlueText procedure to set the ForeColor property of the edit box to Blue and then update the status bar with the appropriate message. You then call the BlueText procedure from the Click event of the Blue toolbar button.

If the user clicks on the Uppercase button on the toolbar, you call UppercaseText, which uses the ToUpper method to convert all the text held in EditText to uppercase text:

‘Make the text uppercase

EditText = EditText.ToUpper

197

Chapter 6

Likewise, if the user clicks on the Lowercase button, you call LowercaseText, which uses the ToLower method to convert all the text held in EditText to lowercase text:

‘Make the text lowercase

EditText = EditText.ToLower

Each of these procedures is called from the Click event of the appropriate toolbar buttons, and these procedures also update the message in the status bar to reflect whether the text has been changed to red, blue, uppercase, or lowercase.

Understanding Focus

There’s a problem with your Text Editor project. When you select another window and then switch back to the Text Editor window, the entire text in the box is highlighted. This happens because the focus has been set to the TextBox control. The control that has focus is the control that is currently selected, as shown in Figure 6-15. For example, if you have two buttons on a form, the code in the Click event handler for the button that has focus will be executed if you press Return.

Figure 6-15

If there are several text boxes on a form, any text you type will be entered into the text box that currently has the focus.

You can move focus between controls at run time by pressing the Tab key. For example, if the user of the form shown in Figure 6-15 pressed the Tab key, focus would jump to the “I do not” button. If the user pressed the Tab key again, focus would jump back to the “I have focus” button.

The order in which the focus moves between the controls on a form is not arbitrary. As you place controls on a form, they are assigned a value for their TabIndex property. The first control to be placed on the form has a TabIndex of 0, the second 1, the third 2, and so on. This is the same order in which the controls will have the focus as you tab through them. If you have placed all your controls on the form and are not happy with the resulting tab order, you can manually change it yourself by using the Properties window to set the TabIndex properties of the controls.

Note that, although labels have a TabIndex property, it is not possible to tab to them at run time. Instead, the focus moves to the next control that can receive it, such as a text box or button.

Visual Basic 2005 has a very handy feature for displaying the tab order of your controls. Select View Tab Order, and your form will look something like Figure 6-16.

The tab order shown in the figure represents the order in which you placed your controls on the form. To remove the numbers, just select View Tab Order once more.

198

Building Windows Applications

Figure 6-16

Using Multiple Forms

All Windows applications have two types of windows: normal windows and dialog boxes. A normal window provides the main user interface for an application. For example, if you use Word, you use a normal window for editing your documents.

On occasion, the application will display a dialog box when you want to access a special feature. This type of window “hijacks” the application and forces you to use just that window. For example, when you select the Print option in Word, a dialog box appears, and from that point on, until you close the dialog by clicking OK, Cancel, or the close box, you can’t go back and change the document — the only thing you can use is the Print dialog box itself. Forms that do this are called modal. While they’re up, you’re in that mode.

Dialog boxes are discussed in more detail in Chapter 7. For now, you can focus on adding additional forms to your application. The form that you add in the next exercise is a simple modal form.

Help About

Most applications have an About dialog box that describes the application’s name and copyright information. As you already have a toolbar button for this feature, you’ll want to create this form now.

Try It Out

Adding an About Box

1.To add a new form to the project, you need to use the Solution Explorer. Right click the Text Editor project and select Add Windows Form. In the Add New Item – Text Editor dialog box, shown in Figure 6-17, select the About Box in the Templates pane, enter About.vb in the Name field, and click the Add button to create the new form.

199

Chapter 6

Figure 6-17

2.When the form’s Designer appears, you’ll notice that all of the normal details that are shown in an About dialog box are already on the form. This includes such items as the product name, version number, copyright information, etc.

3.Right-click the form and choose View Code from the context menu.You’ll notice that the Load event for the form already contains a significant amount of code to populate the details on the About form. There is a TODO comment in the code that informs you that you need to update the assembly information for the application.

4.Right-click the project in the Solution Explorer and choose Properties from the context menu. Click the Assembly Information button in the Application pane of the Text Editor properties to display the Assembly Information dialog box. Edit the information in this dialog box as shown in Figure 6-18 and then click OK to close this dialog box.

Figure 6-18

200

Building Windows Applications

5.You need to write a procedure that will display the About dialog box, so add this code to the TextEditor form:

Public Sub ShowAboutBox() ‘Display the About dialog box Dim objAbout As New About objAbout.ShowDialog(Me)

End Sub

6.Finally, you need to call ShowAboutBox when the Help About button on the toolbar is clicked. In the Class Name combo box at the top of the Code Editor, select tbrHelpAbout and in the Method Name combo box, select the Click event. Add the following highlighted code to the Click event handler:

Private Sub tbrHelpAbout_Click(ByVal sender As Object, _

ByVal e As System.EventArgs) Handles tbrHelpAbout.Click

‘Display the About dialog box

ShowAboutBox()

End Sub

7.Run the project and click on the Help About button. You should see the dialog box shown in Figure 6-19.

Figure 6-19

How It Works

There are a variety of prebuilt forms provided in Visual Studio 2005, as was shown in Figure 6-17. You choose to add the About Box form to your project to display an About dialog box from your application.

When the About form starts, it will fire the Load event, and this event already has the appropriate code written to load the fields on the form. You’ll notice that this code makes efficient use of the My. Application.AssemblyInfo namespace to retrieve the appropriate information from your application’s assembly for the About form:

201

Chapter 6

Private Sub About_Load(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles MyBase.Load

Set the title of the form. Dim ApplicationTitle As String

If My.Application.AssemblyInfo.Title <> “” Then ApplicationTitle = My.Application.AssemblyInfo.Title

Else

ApplicationTitle = System.IO.Path.GetFileNameWithoutExtension( _ My.Application.AssemblyInfo.Name)

End If

Me.Text = String.Format(“About {0}”, ApplicationTitle)

Initialize all of the text displayed on the About Box.

TODO: Customize the application’s assembly information in the

“Application” pane of the project

properties dialog (under the “Project” menu). Me.LabelProductName.Text = My.Application.AssemblyInfo.ProductName Me.LabelVersion.Text = String.Format(“Version {0}”, _

My.Application.AssemblyInfo.Version.ToString) Me.LabelCopyright.Text = My.Application.AssemblyInfo.LegalCopyright Me.LabelCompanyName.Text = My.Application.AssemblyInfo.CompanyName Me.TextBoxDescription.Text = My.Application.AssemblyInfo.Description

End Sub

The assembly information that you modified in the Assembly Information dialog box is used to populate the fields on your About form. If you added the text John Wiley && Sons, Inc. to the Company and Copyright fields in the Assembly Information dialog box as shown in Figure 6-18, you’ll have noticed that two consecutive ampersands were used in John Wiley && Sons, Inc. The reason behind this is that the labels on your About form treat a single ampersand as the start of a code representing a special character. Two consecutive ampersands is then the code for the ampersand character itself.

To display another form, you have to create a new instance of it. That’s exactly what you do in the ShowAboutBox procedure. Once you have created a new instance of the form, you use the ShowDialog method to show the About form modally. When you pass the Me keyword as a parameter to the ShowDialog method, you are specifying that the TextEditor form is the owner of the dialog being shown; in this case the About form:

Public Sub ShowAboutBox() ‘Display the About dialog box Dim objAbout As New About objAbout.ShowDialog(Me)

End Sub

To call the ShowAboutBox procedure, you had to add code to the Click event of the HelpAbout button on the toolbar:

Private Sub tbrHelpAbout_Click(ByVal sender As Object, _

ByVal e As System.EventArgs) Handles tbrHelp.Click

‘Display the About dialog box ShowAboutBox()

End Sub

202

Building Windows Applications

So, with very little effort and a minimal amount of code, you have added a lot of functionality to your Text Editor application. You can see firsthand how Visual Studio 2005 provides productivity and timesaving features such as prebuilt forms.

Summar y

This chapter discussed some of the more advanced features of Windows forms and the commonly used controls. It discussed the event-driven nature of Windows and showed three events that can happen to a button (namely Click, MouseEnter, and MouseLeave).

You created a simple application that allowed you to enter some text and then choose between counting the number of characters or the number of words by using radio buttons.

You then turned your attention to building a more complex application that allowed you to edit text by changing its color or its case. This application showed how easy it was to build an application with toolbars and status bars. You even added an About dialog box to display basic information about your application such as the application title, description, version number, and copyright information.

To summarize, you should now know how to:

Write code to respond to control events

Set properties on controls to customize their look and behavior

Use the ToolStrip and StatusStrip controls

Display other forms in your application

Exercises

Exercise 1

Create a Windows application with two buttons. Add code to the MouseUp event for the first button to display a MessageBox with a message that the event has fired. Add code to the LostFocus event for the first button to also display a MessageBox with a message that the button has lost focus.

Exercise 2

Create a Windows application with a toolbar and status bar. At the bottom of the IDE, right-click the ToolStrip control and select the Insert Standard Items menu item to have the standard buttons added to the control. For the Click event for each of the ToolStripButton controls, display a message in the status bar indicating which button was clicked.

203

7

Displaying Dialog Boxes

Visual Basic 2005 provides several built-in dialog boxes that help you provide a rich user interface in your front-end applications. These dialog boxes provide the same common user interface that is found in most Windows applications. They also provide many properties and methods that allow you to customize these dialog boxes to suit your needs while still maintaining the standard look of Windows applications.

In this chapter, you will learn about the following:

Creating a message box using different buttons and icons

Creating an Open dialog box that enables you to open files

Creating a Save dialog box that enables you to save files

Creating a Font dialog box that enables you to apply the selected font to text

Creating a Color dialog box that enables you to define and select custom colors

Creating a Print dialog box that prints text from your application

This chapter explores these dialog boxes in depth and will show how you can use them in your Visual Basic 2005 applications to help you build a more professional looking application for your users.

The MessageBox Dialog Box

The MessageBox dialog box is one of those dialog boxes that you will use often as a developer. This dialog box enables you to display custom messages to your users and accept their input regarding the choice that they have made. This dialog box is very versatile; you can customize it by displaying a variety of icons with your messages and by choosing which buttons to display.

In the day-to-day operation of a computer, you have seen message boxes that display one of the icons shown in Figure 7-1. In this section, you learn how to create and display message boxes that use these icons.