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

Beginning Visual Basic 2005 (2006)

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

Chapter 8

‘Call the selectAllToolStripMenuItem_Click procedure

selectAllToolStripMenuItem_Click(sender, e) End Sub

18.That’s all the code that you need to add to implement your own context menu. Pretty simple, huh? Now run your project to see your context menu in action and test it. You can test the context menu by clicking each of the context menu items shown. They will perform the same functions as their counterparts in the toolbar and Edit menu.

Do you see the difference in your context menu from the one shown in Figure 8-9? Your context menu has a cleaner look and shows the icons for the various menu items. There is one other subtle difference: Your menu items are all enabled when some of them shouldn’t be. You’ll rectify this in the next Try It Out.

How It Works

The ContextMenuStrip works in the same manner as the MenuStrip, and you should have been able to follow along and create a context menu with ease. You may have noticed that you use a prefix of context for your context menu names in this exercise. This will distinguish these menu items as context menu items and will also group these menu items together in the Class Name combo box in the Code Editor, as you probably already noticed.

The code you added here was a no-brainer, as you have already written the code to perform undo, cut, copy, and paste operations. In this exercise, you merely call the corresponding menu item procedures in your Click event handlers for the context menu items.

Enabling and Disabling Menu Items and Toolbar Buttons

Now that you have implemented a context menu and have it functioning, you are ready to write some code to complete the functionality in your application. In this next Try It Out, you will implement the necessary code to enable and disable menu items, context menu items, and toolbar buttons.

Try It Out

Creating Context Menus

1.You need to create a procedure that can be called to toggle all of the Edit menu items, toolbar buttons, and context menu items, enabling and disabling them as needed. They will be enabled and disabled based upon what should be available to the user. You should call this procedure ToggleMenus, so stop your program and add the following procedure at the end of your existing code.

Private Sub ToggleMenus()

‘Declare a TextBox object and set it to the ActiveControl Dim objTextBox As TextBox = Me.ActiveControl

‘Toggle the Undo menu items undoToolStripMenuItem.Enabled = objTextBox.CanUndo

contextUndoToolStripMenuItem.Enabled = objTextBox.CanUndo

‘Toggle the Cut toolbar button and menu items cutToolStripButton.Enabled = objTextBox.SelectionLength cutToolStripMenuItem.Enabled = objTextBox.SelectionLength contextCutToolStripMenuItem.Enabled = objTextBox.SelectionLength

266

Creating Menus

‘Toggle the Copy toolbar button and menu items copyToolStripButton.Enabled = objTextBox.SelectionLength copyToolStripMenuItem.Enabled = objTextBox.SelectionLength contextCopyToolStripMenuItem.Enabled = objTextBox.SelectionLength

‘Toggle the Paste toolbar button and menu items pasteToolStripButton.Enabled = My.Computer.Clipboard.ContainsText pasteToolStripMenuItem.Enabled = My.Computer.Clipboard.ContainsText contextPasteToolStripMenuItem.Enabled = _

My.Computer.Clipboard.ContainsText

‘Toggle the Select All menu items selectAllToolStripMenuItem.Enabled = _

objTextBox.SelectionLength < objTextBox.Text.Length contextSelectAllToolStripMenuItem.Enabled = _

objTextBox.SelectionLength < objTextBox.Text.Length

End Sub

That’s it! All of that code will toggle the Edit menu items, the context menu items, and the toolbar buttons. Now all you need is to figure out when and where to call this procedure.

2.Since you are checking for only the two text boxes on your form, you can call the ToggleMenu procedure when the user moves the mouse into a text box. This way, you will toggle the Edit menu items and toolbar buttons when the user is in a text box, and the code will be applied against the text box that you are in. To do this, select TextBox1 in the Class Name combo box and the MouseMove event in the Method Name combo box. Add the following highlighted code to the MouseMove event handler:

Private Sub TextBox1_MouseMove(ByVal sender As Object, _

ByVal e As System.Windows.Forms.MouseEventArgs) Handles TextBox1.MouseMove

‘Toggle the menu items and toolbar buttons

ToggleMenus()

End Sub

3.Repeat this process for the second text box on the form and add the same code:

Private Sub TextBox2_MouseMove(ByVal sender As Object, _

ByVal e As System.Windows.Forms.MouseEventArgs) Handles TextBox2.MouseMove

‘Toggle the menu items and toolbar buttons

ToggleMenus()

End Sub

4.Now run your project again. Once the form has been displayed, click in the first text box and enter some text. Then, right-click in the text box to display your context menu. Now the context menu has the appropriate menu items enabled as shown in Figure 8-11.

Notice also that the appropriate toolbar buttons are also enabled and disabled. If you click the Edit menu, you will see that the appropriate menu items there are also enabled and disabled. If you click the Select All menu item or context menu item, you see the toolbar buttons change as well as the menu items under the Edit menu and context menu.

267

Chapter 8

Figure 8-11

How It Works

The first thing that you do in the ToggleMenus procedure is to declare an object and set it equal to the active TextBox control. You saw this in the “Coding the Edit Menu” Try It Out exercise, and this object has all of the properties that the active text box has:

‘Declare a TextBox object and set it to the ActiveControl Dim objTextBox As TextBox = Me.ActiveControl

The first Edit menu item is Undo, so you start with that one. The TextBox class has a property called CanUndo, which returns a True or False value indicating whether or not the last operation performed in the text box can be undone.

You use the CanUndo property to set the Enabled property of the Edit menu item. The Enabled property is set using a Boolean value, which works out great, because the CanUndo property returns a Boolean value. The following code shows how you set the Enabled property of the Undo menu item and context menu item:

‘Toggle the Undo menu items undoToolStripMenuItem.Enabled = objTextBox.CanUndo contextUndoToolStripMenuItem.Enabled = objTextBox.CanUndo

The next menu item in the Edit menu that you wrote code for is the Cut menu item. This time you use the SelectionLength property of your TextBox object. SelectionLength returns the number of characters selected in a text box. You can use this number to act as a True or False value because a value of False in Visual Basic 2005 is 0 and a value of True is 1. Since the value of False is always evaluated first, any number other than 0 evaluates to True.

Therefore, if no text is selected, the SelectionLength property will return 0, and you will disable the Cut toolbar button, Cut menu item, and Cut context menu item. If no text is selected, you don’t want to allow the user to perform this operation:

‘Toggle the Cut toolbar button and menu items cutToolStripButton.Enabled = objTextBox.SelectionLength cutToolStripMenuItem.Enabled = objTextBox.SelectionLength contextCutToolStripMenuItem.Enabled = objTextBox.SelectionLength

268

Creating Menus

The next menu item in the Edit menu is the Copy menu item. Again, you use the SelectionLength property to determine whether any text is selected in the text box and to set the Enabled property appropriately based on the value returned by the SelectionLength property:

‘Toggle the Copy toolbar button and menu items copyToolStripButton.Enabled = objTextBox.SelectionLength copyToolStripMenuItem.Enabled = objTextBox.SelectionLength contextCopyToolStripMenuItem.Enabled = objTextBox.SelectionLength

The next menu item in the Edit menu is the Paste menu item. Setting the Enabled property of this menu item requires a little more work.

You query the ContainsText property of the My.Computer.Clipboard object to receive a Boolean value indicating whether the Clipboard contains any text. Using this return value you can set the Enabled property of the Paste toolbar button, Paste menu item, and context menu item as shown in the following code:

‘Toggle the Paste toolbar button and menu items pasteToolStripButton.Enabled = My.Computer.Clipboard.ContainsText pasteToolStripMenuItem.Enabled = My.Computer.Clipboard.ContainsText contextPasteToolStripMenuItem.Enabled = _

My.Computer.Clipboard.ContainsText

The last Edit menu item is the Select All menu item. Again, you use the SelectionLength property to determine whether any text has been selected. If all of the text has been selected, then you set the Enabled property to False, and set it to True at all other times. To do so, you compare the length of the selected text to the length of the text in the text box:

‘Toggle the Select All menu items selectAllToolStripMenuItem.Enabled = _

objTextBox.SelectionLength < objTextBox.Text.Length contextSelectAllToolStripMenuItem.Enabled = _

objTextBox.SelectionLength < objTextBox.Text.Length

To enable and disable the menu items, context menu items and toolbar buttons, you have to call the ToggleMenus procedure. The best place to do this is in the MouseMove event of the text boxes. The MouseMove event is fired when the mouse is moved over the control, which typically indicates that the user is about to click in the text box and do something:

Private Sub TextBox1_MouseMove(ByVal sender As Object, _

ByVal e As System.Windows.Forms.MouseEventArgs) Handles TextBox1.MouseMove

‘Toggle the menu items and toolbar buttons ToggleMenus()

End Sub

269

Chapter 8

Summar y

This chapter has looked at how to implement menus, menu items, and submenu items. You also saw how to implement multiple toolbars, although that was not the focus of the chapter. Through practical hands-on exercises you have seen how to create menus, menu items, and submenu items. You have also seen how to add access keys, shortcut keys, and images to these menu items.

Since you used the Edit menu in the Try It Outs, you have also seen how easy it is to implement basic editing techniques in your application by using the properties of the TextBox control and the Clipboard object. You can see how easy it is to provide this functionality to your users — something users have come to expect in every good Windows application.

You also explored how to create and implement context menus and to override the default context menus provided by Windows. Since you had already coded the procedure to implement undo, cut, copy, and paste operations, you simply reused that code in your context menus.

Now that you have completed work in this chapter, you should know how to:

Add a MenuStrip control to your form and add menus, menu items, and submenu items.

Customize the menu items with a check mark.

Add access keys and shortcut keys to your menu items.

Add a ContextMenuStrip control to your form and add menu items.

Use the properties of the TextBox control to toggle the Enabled property of menu items.

Exercise

To give your Menus project the standard look of a typical Windows application, add a StatusStrip control to the form and add the necessary code to display a message when text is cut, copied, or pasted.

270

9

Debugging and Error

Handling

Debugging is an essential part of any development project, as it helps you find errors in your code and in your logic. Visual Studio 2005 has a sophisticated debugger built right into the development environment. This debugger is the same for all languages that Visual Studio 2005 supports. So once you have mastered debugging in one language, you can debug in any language that you can write in Visual Studio 2005.

No matter how good your code is, there are always going to be some unexpected circumstances that will cause your code to fail. If you do not anticipate and handle errors, your users will see a default error message about an unhandled exception, which is provided by the common language run-time package. This is not a user-friendly message and usually does not clearly inform the user about what is going on or how to correct it.

This is where error handling comes in. Visual Studio 2005 also provides common structured errorhandling functions that are used across all languages. These functions allow you to test a block of code and catch any errors that may occur. If an error does occur, you can write your own userfriendly message that informs the user of what happened and how to correct it, or you can simply handle the error and continue processing.

This chapter looks at some of the debugging features available in Visual Studio 2005 and provides a walk-through of debugging a program. You examine how to set breakpoints in your code to stop execution at any given point, how to watch the value of a variable change, and how to control the number of times a loop can execute before stopping. All of these can help you determine just what is going on inside your code. Finally, this chapter takes a look at the structured error-handling functions provided by Visual Studio 2005.

In this chapter, you will:

Examine the major types of errors that you may encounter and how to correct them

Examine and walk through debugging a program

Examine and implement error handling in a program

Chapter 9

Major Error Types

Error types can be broken down into three major categories: syntax, execution, and logic. This section will show you the important differences among these three types of errors and how to correct them.

Knowing what type of errors are possible and how to correct them will significantly speed up the development process. Of course, sometimes you just can’t find the error on your own. Don’t waste too much time trying to find errors in your code by yourself in these situations. Coming back to a nagging problem after a short coffee break can often help you crack it. Otherwise, ask a colleague to have a look at your code with you; two pairs of eyes are often better than one in these cases.

Syntax Errors

Syntax errors, the easiest type of errors to spot and fix, occur when the code you have written cannot be “understood” by the compiler because instructions are incomplete, supplied in unexpected order, or cannot be processed at all. An example of this would be declaring a variable of one name and misspelling this name in your code when you set or query the variable.

The development environment in Visual Studio 2005 has a really sophisticated syntax-checking mechanism, making it hard, but not impossible, to have syntax errors in your code. It provides instant syntax checking of variables and objects and will let you know immediately when you have a syntax error.

Suppose you try to declare a variable as Private in a procedure. Visual Studio 2005 will underline the declaration with a blue wavy line indicating that the declaration is in error. If the Integrated Development Environment (IDE) can automatically correct the syntax error, you’ll see a little orange rectangular box at the end of the blue wavy line, as shown in Figure 9-1, indicating that AutoCorrect options are available for this syntax error. AutoCorrect is a feature of Visual Studio 2005 that provides error correction options that the IDE will suggest to correct the error.

Figure 9-1

When you hover your mouse over the code in error, you’ll receive a ToolTip, telling you what the error is, and a small gray box with a red circle and a white exclamation point. If you then move your mouse into the gray box, a down arrow will appear, shown in Figure 9-2, to let you know that a dialog box is available with some suggested error correction options.

272

Debugging and Error Handling

Figure 9-2

Clicking the down arrow or pressing Shift+Alt+F10 will cause the Error Correction Options dialog box to appear as shown in Figure 9-3. This dialog box presents one or more choices to you for correcting the error. In this instance, there is only one choice to correct the syntax error as shown in the dialog box in Figure 9-3.

Notice that the dialog box shows you how your code can be corrected: by replacing the Private keyword with the Dim keyword. The sample code displayed in the dialog box has your offending statement in strikethrough and the suggested correction preceding it. Above the code in the dialog box is a hyperlink that will replace the Private keyword with the Dim keyword. Click this link to apply the fix to your code.

Figure 9-3

Another option available for reviewing all the errors in your code is the Error List window. This window displays a grid with all the errors’ descriptions, the files they exist in, and the line numbers and column numbers of the error. If your solution contains multiple projects, it will also display the project that each error exists in.

The Error List can be accessed by clicking the Error List tab at the bottom of the IDE. Once the Error List window is displayed, you can double-click any error to be taken to that specific error in your code.

273

Chapter 9

Sometimes you’ll receive warnings, displayed with a green wavy line under the code in question. These are just warnings and your code will compile. However, you should heed these warnings and try to correct these errors if possible, because they may produce undesirable results at run time.

As an example, a warning would occur in the line of code shown in Figure 9-3 once the Private keyword was replaced with the Dim keyword. The IDE would give you a warning that the variable, strFileName, is unused in the procedure. Simply initializing the variable or referencing the variable in code would cause this warning to go away.

Keep in mind that you can hover your mouse over errors and warnings in your code to cause the appropriate ToolTip to be displayed informing you of the problem. As a reminder, if the IDE can provide the AutoCorrect feature for errors, the blue wavy line will contain an orange rectangular box at the end of the blue wavy line.

The IDE also provides IntelliSense to assist in preventing syntax errors. IntelliSense provides a host of features such as providing a drop-down list of members for classes, structures, and namespaces as shown in Figure 9-4. This enables you to choose the correct member for the class, structure, or namespace that you are working with. It also provides ToolTip information for the selected member or method, also shown in Figure 9-4.

Figure 9-4

These IntelliSense features provide two major benefits. First, you do not have to remember all the available members for the class. You simply scroll through the list to find the member that you want to work

with. To select the member in the list that you want to work with, you press the Tab or Enter key or doubleclick the member. Second, the features help to prevent syntax errors because you are less likely to misspell member names or try to use members that do not exist in the given class.

Another great feature of IntelliSense is that it provides a parameter list for the method that you are working with. IntelliSense will list the number, names, and types of the parameters required by the function, as shown in Figure 9-4. This is also a time saver, as you do not have to remember the required parameters for every class member that you work with, or indeed search the product documentation for what you need.

274

Debugging and Error Handling

If the method is overloaded — that is, there are several methods with the same name but different parameters — the ToolTip will indicate this as shown in Figure 9-4 with the text “(+ 1 overloads)”. Also, when you start to work with the member, a pop-up list enables you to scroll through the different overloaded methods, as shown in Figure 9-5 for the Substring method of the String class, by simply clicking the up and down arrows to view the different overloaded methods.

Figure 9-5

Plenty of built-in features in the development environment can help prevent syntax errors. All you need to do is to be aware of these features and take advantage of them to help prevent syntax errors in your code.

Execution Errors

Execution errors (or run-time errors) occur while your program is executing. These errors are often caused because something outside of the application, such as a user, database, or hard disk, does not behave as expected.

Developers need to anticipate the possibility of execution errors and build appropriate error-handling logic. Implementing the appropriate error handling will not prevent execution errors, but will allow you to handle them either by gracefully shutting down your application or bypassing the code that failed and giving the user the opportunity to perform that action again. Error handling is covered later in this chapter.

The best way to prevent execution errors is to try anticipating the error before it occurs and to use error handling to trap and handle the error. You must also thoroughly test your code before deploying it.

Most execution errors can be found while you are testing your code in the development environment. This allows you to handle the errors and debug your code at the same time. You can then see what type of errors may occur and implement the appropriate error-handling logic. Debugging, where you find and handle any execution errors that may crop up, is covered later in the “Debugging” section.

Logic Errors

Logic errors (or semantic errors) give unexpected or unwanted results because you did not fully understand what the code you were writing did. Probably the most common logic error is an infinite loop:

Private Sub PerformLoopExample()

Dim intIndex As Integer

Do While intIndex < 10

‘some logic here

Loop End Sub

275