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

Beginning Visual Basic 2005 (2006)

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

Chapter 7

Although you used the controls from the Toolbox for all of these dialog boxes, except the MessageBox dialog box, remember that these controls can also be used as normal classes. This means that the classes that these dialog boxes use expose the same properties and methods that you’ve seen, whether you are selecting a control visually or writing code using the class. You can define your own objects and set them to these classes, and then use the objects to perform the tasks that you performed using the controls. This provides better control over the scope of the objects. For example, you could define an object, set it to the OpenDialog class, use it, and then destroy it all in the same procedure. This method uses resources only in the procedure that defines and uses the OpenDialog class, and reduces the size of your executable.

To summarize, you should now know how to:

Use the MessageBox dialog box to display messages

Display icons and buttons in the MessageBox dialog box

Use the OpenFileDialog control and read the contents of a file

Use the SaveFileDialog control and save the contents of a text box to a file

Use the FontDialog control to set the font and color of text in a text box

Use the ColorDialog control to set the background color of your form

Use the PrintDialog control to print text

Use the FolderBrowserDialog control to get a selected folder

Exercises

Exercise 1

Create a simple Windows application with a TextBox control and two Button controls. Set the buttons to open a file and to save a file. Use the OpenFileDialog class (not the control) and the SaveFileDialog class to open and save your files.

Hint: To use the corresponding classes for the controls use the following statements:

Dim objOpenFileDialog As New OpenFileDialog

Dim objSaveFileDialog As New SaveFileDialog

Exercise 2

Create a simple Windows application with a Label control and a Button control. Set the button to display the Browse For Folder dialog box with the Make New Folder button displayed. Use My Documents as the root folder at which the dialog starts browsing. Use the FolderBrowserDialog class (not the control) and display the selected folder in the label on your form.

246

8

Creating Menus

Menus are a part of every good application and provide not only an easy way to navigate within an application but also useful tools for working with that application. Take, for example, Visual Studio 2005. It provides menus for navigating the various windows that it displays and useful tools for making the job of development easier through menus and context menus (also called pop-up menus) for cutting, copying, and pasting code. It also provides menu items for searching through code.

This chapter takes a look at creating menus in your Visual Basic 2005 applications. You explore how to create and manage menus and submenus and how to create context menus and override the default context menus. Visual Studio 2005 provides two menu controls in the Toolbox, and you will be exploring both of these.

In this chapter, you will:

Create menus

Create submenus

Create context menus

Understanding Menu Features

The MenuStrip control in Visual Studio 2005 provides several key features. First and foremost, it provides a quick and easy way to add menus, menu items, and submenu items to your application. It also provides a built-in editor that allows you to add, edit, and delete menu items at the drop of a hat.

The menu items that you create may contain images, access keys, shortcut keys, and check marks as well as text labels.

Chapter 8

Images

Everyone has seen images on the menus in their applications, such as Microsoft Word and even Visual Studio 2005 itself. Up until now, developers were unable to create menu items with images without some custom programming or purchasing a third-party control. Visual Studio 2005 now provides an Image property for a menu item that makes adding an image to your menu items a breeze.

Access Keys

An access key (also known as an accelerator key) enables you to navigate the menus using the Alt key and a letter that is underlined in the menu item. When the access key is pressed, the menu will appear on the screen, and the user can navigate through it using the arrow keys or the mouse.

Shortcut Keys

Shortcut keys enable you to invoke the menu item without displaying the menus at all. Shortcut keys usually consist of a control key and a letter, such as Ctrl+X to cut text.

Check Marks

A check mark symbol can be placed next to a menu item in lieu of an image, typically to indicate that the menu item is being used. For example, if you click the View menu in Visual Studio 2005 and then select the Toolbars menu item, you see a submenu that has many submenu items, some of which have check marks. The submenu items that have check marks indicate the toolbars that are currently displayed.

Figure 8-1 shows many of the available features that you can incorporate into your menus. As you can see, this sample menu provides all the features that were just mentioned plus a separator. A separator looks like a raised ridge and provides a logical separation between groups of menu items.

Menu Menu Item Shortcut Key

Separator

Check Mark

Image Access Key

Sub Menu Item

Figure 8-1

 

Figure 8-1 shows the menu the way it looks when the project is being run. Figure 8-2 shows how the menu looks in Design mode.

248

Creating Menus

Figure 8-2

The first thing that you’ll notice when using the MenuStrip control is that it provides a means to allow you to add another menu, menu item, or submenu item quickly. Each time you add one of these, another blank text area is added.

The second thing that you may notice is the absence of underlines indicating the access keys, since they are not displayed in Design mode.

The Properties Window

While you are creating or editing a menu, the Properties window displays the available properties that can be set for the menu being edited, as shown in Figure 8-3, which shows the properties for the Toolbars menu item.

Figure 8-3

You can create as many menus, menu items, and submenu items as you need. You can even go as deep as you need to when creating submenu items by creating another submenu within a submenu.

249

Chapter 8

Keep in mind, though, that if the menus are hard to navigate, or if it is hard to find the items your users are looking for, the users will rapidly lose faith in your application.

You should stick with the standard format for menus that you see in most Windows applications today. These are the menus that you see in Visual Studio 2005, Microsoft Word, or Microsoft Outlook. For example, you always have a File menu and an Exit menu item in the File menu to exit from the application. If your application provides cut, copy, and paste functionality, you would place these menu items in the Edit menu, and so on.

The MSDN library that was installed with Visual Studio 2005 contains a section on User Interface Design and Development. This section contains many topics that address the user interface and the Windows user interface. You can explore these topics for more details on Windows user-interface design-related topics.

The key is to make your menus look and feel like the menus in other Windows applications so that the users can feel comfortable using your application. This way they do not feel like they have to learn the basics of Windows all over again. Some menu items will be specific to your application but the key to incorporating them is to ensure that they fall into a general menu category that users are familiar with or to place them in your own menu category. You would then place this new menu in the appropriate place in the menu bar, generally in the middle.

Creating Menus

Now you move on and see how easy it is to create menus in your applications. In the following Try It Out, you are going to create a form that contains a menu bar, two toolbars, and two text boxes. The menu bar will contain five menus: File, Edit, View, Tools, and Help, and a few menu items and submenu items. This will enable you to fully exercise the features of the menu controls. Since there are several steps involved in building this application, this process will be broken down into several sections, the first of which is “Designing the Menus.”

Designing the Menus

You will be implementing code behind the menu items to demonstrate the menu and how to add code to your menu items, so let’s get started.

Try It Out

Creating Menus

1.Start Visual Studio 2005 and click File New Project. In the New Project dialog box, select Windows Application in the Templates pane and enter a project name of Menus in the Name field. Click the OK button to have the project created.

2.Click the form in the Forms Designer and set the following properties of the form:

Size to 300, 168.

StartPosition to CenterScreen.

Text to Menu Demo.

250

Creating Menus

3.Drag a MenuStrip control from the Toolbox and drop it on your form. It will be automatically positioned at the top of your form. The control will also be added to the bottom of the development environment, just like the dialog box controls discussed in Chapter 7.

4.At the bottom of the IDE, right click on the MenuStrip1 control and select the Insert Standard Items context menu item to have the standard menu items automatically inserted.

5.Notice that there is a box to the right of the Help menu as shown in Figure 8-4. This is where you can type the next menu item. Or you can use the Items Collection Editor, which is what you will do now.

In the Properties window, click the ellipsis dots (...) button next to the Items property. In the Items Collection Editor dialog box, click the Add button to add a new menu item.

To be consistent with the current naming standard already in use with the other menu items, set the Name property for this new menu item to viewToolStripMenuItem.

Now set the Text property to &View. An ampersand (&) in the menu name provides an access key for the menu or menu item. The letter before which the ampersand appears will be the letter used to access this menu item in combination with the Alt key. So for this menu, you will be able to access and expand the View menu by pressing Alt+V. You’ll see this when you run your project later.

You want to position this menu between the Edit and Tools menu so click the up arrow to the right of the menu items until the View menu is positioned between editToolStripMenuItem and toolsToolStripMenuItem in the list.

Figure 8-4

6.Now locate the DropDownItems property and click the ellipsis dots button next to it so that you can add menu items beneath the View menu. A second Items Collection Editor will appear, and its caption will read “Items Collection Editor (viewToolStripMenuItem.DropDownItems)”.

There will only be one menu item under the View menu, and that will be Toolbars. Click the Add button in the Item Collections Editor to add a MenuItem.

Again, you want to be consistent with the naming standard already being used so set the Name property to toolbarToolStripMenuItem. Then set the Text property to &Toolbars.

7.You want to add two submenu items under the Toolbars menu item, so locate the DropDownItems property and click the ellipsis button next to it.

In the Item Collections Editor, click the Add button to add a new menu item. Set the Name property for this submenu item to mainToolStripMenuItem and the Text property to &Main.

251

Chapter 8

When you add a toolbar to this project, it will be displayed by default, so this submenu item should be checked to indicate that the toolbar is displayed. Set the Checked property to True to cause this submenu item to be checked by default and the CheckOnClick property to True to allow the check mark next to this submenu item to be toggled on and off.

8.The next submenu item that you add is Formatting. Click the Add button to add a new menu item and set the Name property for this submenu item to formattingToolStripMenuItem and the Text property to &Formatting.

Since this toolbar will not be shown by default, you need to leave the Checked property set to False. You do, however, need to set the CheckOnClick property to True so that the submenu item can toggle the check mark on and off.

Keep clicking the OK button in the Items Collection Editors until all of the editors are closed.

9.If you run your project at this point and click the View menu and then the Toolbars menu item, you see the submenu items as shown in Figure 8-5. You can also click the other menus and see their menu items.

Figure 8-5

How It Works

Visual Studio 2005 takes care of a lot of the details for you by providing the Insert Standard Items context menu item in the MenuStrip control. By clicking this menu item, Visual Studio 2005 created the standard menus and menu items found in most common applications. This allows you to concentrate on only the menus and menu items that are custom to your application, which is what you did by adding the View menu, Toolbars menu item, and Main and Formatting submenu items.

Adding Toolbars and Controls

In this section, you add the toolbars and buttons for the toolbars that the application needs. The menus created in the previous section will control the displaying and hiding of these toolbars. You will also be adding a couple of TextBox controls that will be used in the application to cut, copy, and paste text using the toolbar buttons and menu items.

Try It Out

Adding Toolbars and Controls

1.You need to add two toolbars to the form, so locate the ToolStrip control in the Toolbox and drag and drop it on your form; it automatically aligns itself to the top of the form below the menu. Set the Name property to tspFormatting and its Visible property to False, because you don’t want this toolbar to be shown by default.

252

Creating Menus

2.You want to add four buttons to this toolbar, so click the ellipsis dots button next to the Items property in the Properties window.

In the Items Collection Editor dialog box, click the Add button to add the first button. Since you really won’t be using these buttons, you can accept the default name and ToolTip text for these buttons. Ensure the DisplayStyle property is set to Image, and then click the ellipsis dots button next to the Image property.

In the Select Resource dialog box, click the Import button and browse to C:\Program Files\ Microsoft Visual Studio 8\Common7\VS2005ImageLibrary\bitmaps\commands\high color folder. This path assumes a default installation of Visual Studio 2005. In the Open dialog box, select AlignTableCellMiddleLeftJustHS.bmp and then click the Open button. Next, click the OK button in the Select Resource dialog box to close it.

3.In the Items Collection Editor dialog box, click the Add button again to add the second button. Ensure the DisplayStyle property is set to Image and then set Image property to the Align TableCellMiddleCenter.bmp file.

4.In the Items Collection Editor dialog box, click the Add button again to add the next button. Ensure the DisplayStyle property is set to Image and then set the Image property to the

AlignTableCellMiddleRight.bmp file.

5.Now click the OK button in the Items Collection Editor dialog box to close it.

6.Next, add a second toolbar to the form in the same manner. It aligns itself above the first toolbar. Set its Name property to tspMain. The default toolbar buttons will be fine for this project, so right-click the tspMain control at the bottom of the IDE and select Insert Standard Items from the context menu to have the standard toolbar buttons added.

7.Now add a Panel control from the toolbox to your form and set its Dock property to Fill.

8.Add two TextBox controls to the Panel control and accept their default properties. Their location and size are not important, but they should be wide enough to enter text in. Your completed form should now look similar to the one shown in Figure 8-6. Notice that your second toolbar is not visible since you set its Visible property to False.

Figure 8-6

If you run your project at this point you will see the menus, the main toolbar, and two text boxes. The formatting toolbar is not visible at this point because the Visible property was set to False.

253

Chapter 8

How It Works

You took a look at toolbars in Chapter 6, so review the Text Editor project for details on how the ToolStrip control works. The ToolStrip control, like the MenuStrip control, provides the Insert Standard Items context menu item, which does a lot of the grunt work for you by inserting the standard toolbar buttons, as was shown in Figure 8-6. This without a doubt provides the most efficient means of having the standard toolbar buttons added to the ToolStrip control. You can, of course, rearrange the buttons that have been added and even add new buttons and delete existing buttons.

Because you set the Visible property to False for the tspFormatting ToolStrip control, that control does not take up any space on your form at design time after the control loses focus.

Coding Menus

Now that you have finally added all of your controls to the form, it’s time to start writing some code to make these controls work. First, you have to add functionality to make the menus work. After you have done that, add code to make some of the buttons on the main toolbar work.

Try It Out

Coding the File Menu

1.Start by switching to the Code Editor for the form. In the Class Name combo box at the top of the Code Editor, select newToolStripMenuItem and select the Click event in the Method Name combo box. Add the following highlighted code to the Click event handler:

Private Sub newToolStripMenuItem_Click(ByVal sender As Object, _

ByVal e As System.EventArgs) Handles newToolStripMenuItem.Click

‘Clear the text boxes TextBox1.Text = String.Empty TextBox2.Text = String.Empty

‘Set focus to the first text box TextBox1.Focus()

End Sub

2.Now add the procedure for the New button on the toolbar by selecting newToolStripButton from the Class Name combo box and the Click event from the Method Name combo box. Add the following highlighted code to this procedure:

Private Sub newToolStripButton_Click(ByVal sender As Object, _

ByVal e As System.EventArgs) Handles newToolStripButton.Click

‘Call the newToolStripMenuItem_Click procedure

newToolStripMenuItem_Click(sender, e) End Sub

3.Now select exitToolStripMenuItem from the Class Name combo box and the Click event from the Method Name combo box and add the following highlighted code to the procedure:

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

254

Creating Menus

‘Close the form and end

Me.Close()

End Sub

How It Works

To clear the text boxes on the form in the newToolStripMenuItem_Click procedure, add the following code. All you are doing here is setting the Text property of the text boxes to an empty string. The next line of code sets focus to the first text box by calling the Focus method of that text box:

‘Clear the text boxes TextBox1.Text = String.Empty TextBox2.Text = String.Empty

‘Set focus to the first text box TextBox1.Focus()

Now when you click the New menu item under the File menu, the text boxes on the form are cleared of all text, and TextBox1 will have the focus and will be ready to accept text.

The New button on the toolbar should perform the same function, but you don’t want to write the same code twice. Here you could put the text in the previous procedure in a separate procedure and call that procedure from both the newToolStripMenuItem_Click and newToolStripButton_Click procedures. Instead, you have the code in the newToolStripMenuItem_Click procedure and simply call that procedure from within the newToolStripButton_Click procedure. Since both procedures accept the same parameters, you simply pass the parameters received in this procedure to the procedure you are calling:

‘Call the newToolStripMenuItem_Click procedure

newToolStripMenuItem_Click(sender, e)

Now you can click the New button on the toolbar or click the New menu item on the File menu and have the same results, clearing the text boxes on your form.

When you click the Exit menu item, you want the program to end. In the exitToolStripMenuItem_ Click procedure, you added the following code. The Me keyword refers to the class where the code is executing and, in this case, refers to the form class. The Close method closes the form, releases all resources, and ends the program:

‘Close the form and end

Me.Close()

That takes care of the code for the File menu and its corresponding toolbar button, so you want to move on to the Edit menu and add the code for those menu items.

Try It Out

Coding the Edit Menu

1.The first menu item in the Edit menu is the Undo menu item. Select undoToolStripMenuItem in the Class Name combo box and select the Click event in the Method Name combo box. Add the following highlighted code to the Click event handler:

255