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

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

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

290

C H A P T E R 1 0 L I S T S

Figure 10-21. Adding images to the TreeView gives the list a nice new look that can also be used to provide vital feedback to the user.

Click on the Even Numbers node now and you’ll see the graphic change as the list expands.

But wait—there’s more!

Aside from assigning graphics to a node, you can also specify individual colors for each node in the TreeView, and even ToolTips. This is really handy, for example, if you were writing some kind of check-balancing application and wanted to show certain accounts or categories of spending in red.

Each TreeNode, just like any control in .NET, has BackColor, ForeColor, and ToolTip properties. By setting these up, you can change the look and feel of the control even more. Add a couple more lines of code to the Load event to do just that:

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

ByVal e As System.EventArgs) Handles Button1.Click

TreeView1.Nodes.Clear()

Dim oddNumbers As TreeNode = _ TreeView1.Nodes.Add("Odd", "Odd numbers", 0, 1)

oddNumbers.BackColor = Color.Yellow oddNumbers.ForeColor = Color.Blue oddNumbers.ToolTipText = "The odd numbers"

C H A P T E R 1 0 L I S T S

291

Dim evenNumbers As TreeNode = _ TreeView1.Nodes.Add("Even", "Even numbers", 0, 1)

evenNumbers.BackColor = Color.Blue evenNumbers.ForeColor = Color.Yellow evenNumbers.ToolTipText = "The even numbers"

For i As Integer = 1 To 500

If i Mod 2 = 0 Then

evenNumbers.Nodes.Add(i.ToString())

Else

oddNumbers.Nodes.Add(i.ToString())

End If

Next

End Sub

Run the application now, and the form looks very different, as you can see in Figure 10-22. Also, notice that to get the ToolTips working, you had to add a line of code to turn the ShowNodeToolTips property to True. You can also do this at design time with the Properties window.

Figure 10-22. Each node is like a tiny control; you have complete control over how it looks and even ToolTips to show.

292

C H A P T E R 1 0 L I S T S

Responding to Selections and Finding Nodes

You haven’t looked at selecting nodes yet. The tree view has an event called NodeMouseClick. This event fires whenever the user clicks on a node. You can find out just which node the user clicked on from the event arguments object passed in. Take a look (don’t key this in unless you really want to):

Private Sub TreeView1_NodeMouseClick(ByVal sender As System.Object, _ ByVal e As System.Windows.Forms.TreeNodeMouseClickEventArgs) _ Handles TreeView1.NodeMouseClick

Dim selectedNode As TreeNode = e.Node

Console.WriteLine(selectedNode.Text)

End Sub

To find the selected node, you just call e.Node.

After you find a node in this way, there’s a bunch of stuff you can do with it. You can find out if it has children of its own by examining the Nodes.NodeCount property. This will return an integer telling you exactly how many child nodes it has. In addition, you can call Nodes.Parent to get the TreeNode that the selected node is a child of. If it’s a top-level node with no parents, the return value is Nothing.

You can also quickly find out if the node contains children set with a certain key by calling Nodes.ContainsKey(). You pass in a string for the key that was set when the node was added, and you get back a True or False value. For example:

Dim selectedNode As TreeNode = e.Node

If selectedNode.Nodes.ContainsKey("PrimeNumber") Then

Console.WriteLine("This node contains prime numbers")

End If

Finally, as I mentioned earlier, you can call the Find() method on the Nodes collection of a node to find all nodes matching a certain key. The result is an array of TreeNodes.

Summary

As you can see, .NET gives a great deal of flexibility when it comes to displaying lists of data. In fact, the TreeView control when you really explore it offers a phenomenal amount of power.

When we move on to databases a little later, you’ll see a grid control that does even more than all these lists. You’ll also take a look at how to connect these list controls to a database to automatically show the database contents.

C H A P T E R 1 1

■ ■ ■

Menus and Toolbars

All but the very smallest of quick hack applications have a menu. Even Microsoft’s humble Notepad application includes an extensive menu, allowing you to access the program’s property page, load and save files, reformat text, and a whole lot more besides.

On the subject of Notepad, though, its menus are somewhat “old-school.” They are plain textual menus with the odd shortcut key here and there (Ctrl+S for example, to activate the File Save item) and little more. In recent years, though, Microsoft has shown the world that menus can be a lot more than just lists of text. The leader in terms of user interface standards for Microsoft Windows has always been the Office suite, and the menus in the latest version of Office are light years ahead of Notepad. Take a look at Figure 11-1.

Figure 11-1. The menus in Microsoft Office are known as “rich” menus.

293

294 C H A P T E R 1 1 M E N U S A N D T O O L B A R S

Menu items in Office include graphics in many cases. Menu items that can be toggled on and off highlight the graphic to show when certain options are enabled, and when others are not. These menus are “rich” in the level of graphic feedback they provide to users.

Visual Basic 2005 Express makes it easy to create such rich menus in your own applications. In fact, when you compare the menu creation tools to those in the very first version of Visual Studio .NET, it’s really quite breathtaking to see just how far the development tools have come in just a few short years.

Typically, wherever you have a menu in a Windows application, you also have toolbars. Toolbars appear beneath the menu bar and provide rapid one-click access to common menu items (such as Load and Save, Undo, Cut, Copy and Paste, and so on). In addition, wherever you have a menu and toolbar, you’ll typically also see a status bar, a special form of toolbar that always appears at the bottom of the window to provide vital feedback on what the application is doing. Once again, take a look at Microsoft Word from the Office suite (see Figure 11-2).

Figure 11-2. You’ll frequently find that wherever you have menus, you also have toolbars and status bars.

The first time you look at developing a serious Windows program with all these things, the amount of graphical splendor they convey seems impossibly out of reach to all but the most accomplished developers. Just as with menus, though, the tools to let you build toolbars and status bars in VB Express are very sophisticated and very easy to use.

C H A P T E R 1 1 M E N U S A N D T O O L B A R S

295

The Menu Controls

Visual Basic 2005 Express provides two menu controls. One, the MenuStrip control, lets you build the menu that lives on the top edge of a window. The other, the ContextMenuStrip control, lets you add context-sensitive menus, menus that appear whenever you right-click something that has a context menu attached. You’ve seen context menus in the VB IDE itself, for example, when you right-click an item in the Solution Explorer.

You typically use menu strips to allow access to functionality common to the entire application. Context menus, though, as you’ve seen, tend to be focused on one specific area and one specific piece of data. Take a look at Figure 11-3, for example.

Figure 11-3. Context menus provide functionality specific to an area of the application and the “context” the user is working in.

I made this menu appear by right-clicking on a project in the Solution Explorer. The “context” I was in was the Solution Explorer and project management. The context menu then appears to show me things specific to projects, such as adding new items to the project and so on. Because context menus usually appear only when the user right-clicks something, they are not the most intuitive user interface element in the Toolbox. Unless users know that they can right-click something, the chances are that they might well miss your ornately designed context menu. Therefore, use context menus sparingly, or at the very least add ToolTips to controls to let users know that they can right-click something to bring up such a menu.

Let’s start off with the basics and take a look at how to add a standard menu to a simple window.

296 C H A P T E R 1 1 M E N U S A N D T O O L B A R S

Building a Menu

The menu controls (and the toolbar and status bar controls, for that matter) can be found in the Menus & Toolbars section of the Toolbox (Figure 11-4).

Figure 11-4. The controls to build menus and toolbars are all grouped together in the Toolbox.

To add a menu to a form, just double-click the MenuStrip control, and a blank, empty menu will appear on the form (see Figure 11-5).

Figure 11-5. Double-click the MenuStrip control to add a menu onto a form.

When you add a MenuStrip to a form, the Properties window instantly changes to show properties for the control, as you would expect. However, if you click in the menu, specifically in an area marked Type Here, the Properties window will change to show information relating to a ToolStripMenuItem.

Menus consist of ToolStripMenuItems. Each heading you see on a menu, and each item that appears underneath a menu heading is a ToolStripMenuItem. By clicking on an item and using the Properties window, you can change pretty much any aspect of the item—its colors and font, its name, the image to display alongside it, background color, and more besides. To be frank, though, most people never even touch the Properties window when building menus; for most tasks, simply clicking in a blank area of the menu and typing is enough to set up the menu just the way they like.

C H A P T E R 1 1 M E N U S A N D T O O L B A R S

297

Before we move on to setting up images and shortcuts for menu items, let’s take a quick look at how to build a simple menu and add event handlers to the items.

Try It Out: Creating a Simple Menu

Start up a WinForms project and then drop a MenuStrip control onto the window.

Click in the area of the menu that says Type Here, and type in &File. The leading & symbol tells Windows that you want the first letter of the menu item underlined to make it easy for users to select it by pressing Alt+F. Your menu should now look like mine in Figure 11-6.

Figure 11-6. You can create menu items by simply clicking on an area of the menu and typing.

Notice in the screen shot that as soon as you start typing into a top-level menu item, the menu editor adds two more Type Here items: one to the right of the new menu item, and one underneath. You can use these to add new items to the menu easily. Go ahead and add in a few more options to the File menu so that it looks like Figure 11-7.

Figure 11-7. Add more menu items to the File menu—don’t forget to place an & symbol before the letter in the item that you want to be underlined.

Each time you click to add a new menu item, you’ll see that two more Type Here items appear, even as you move down the menu. This allows you to build up submenus, menus that expand with even more menu items when they are clicked.

You may have also noticed that as you move the mouse over an area for a new menu item, a drop-down icon appears to the right of the blank item. This allows you to add more than just text items to a menu. Move the

298 C H A P T E R 1 1 M E N U S A N D T O O L B A R S

mouse over the menu item underneath Save As and click the drop-down, and you’ll see a submenu appear as in Figure 11-8.

Figure 11-8. You can use the drop-down to the right of a new menu item area to add different types of menu items.

As you can see, menus can also hold separators (which are just lines to space out the items in the menu), combo boxes, and even text boxes. The latter work just the same way that a standard combo box or text box would, but embedded inside a menu.

Choose Separator to add a separator into the list, and then add one more entry to the list, as shown in Figure 11-9.

Figure 11-9. The finished File menu

C H A P T E R 1 1 M E N U S A N D T O O L B A R S

299

Let’s add some code now to the Exit item’s event handler. To do this, double-click the menu item, just as you would double-click any other control to drop into the code editor.

Notice that the default event is a Click event for a menu item. No surprises there, then. There are a lot of other events that you can code up, but just as with menu properties, you’ll rarely find yourself using them.

Type in some code to close the form when the menu item is clicked, like this:

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

Me.Close()

End Sub

That’s all there is to it. As you can see, creating a menu and setting its events behind the scenes really is as simple as working with any other kind of control. Run the program now to make sure everything works, and feel free to play a bit with the menu builder. We’ll catch up in the next section, where we look at graphics and shortcuts.

Adding Images and Shortcuts to a Menu

As you’ve just seen, building a menu is really a no-brainer. If you come from a Visual Basic background, you’ll probably have your jaw on the floor at this point because the menu editor is so much easier than it was in classic VB.

All we did in the previous example was just build up a trivial text-based menu. I mentioned in the introduction that it is now possible to add graphics and other visual wonders to a menu to make your menus look just like they were pulled out of a Microsoft Office application.

The properties that handle images are the Image, ImageAlign, ImageScaling, and ImageTransparentColor properties shown in Figure 11-10.

Figure 11-10. The image properties let you transform the way a menu item looks.