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

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

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

310 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

So if there are no child windows open, you’ll disable the Save menu item. If there are child windows open, though, you’ll enable the Save menu item. Perfect.

Run the program now and you’ll see it works just as we thought, but with a twist. Take a look at Figure 11-22.

Figure 11-22. Where did that Special menu come from on the MdiParent form?

Notice the Special menu item on the main form? That’s the menu item that you created on the child form. At runtime, the active child form will “merge” its menu with that of the parent. So, when a child form is open, the parent automatically shows new menu items that apply to the child. If you click any of the Special menu items to change the child form’s color, you’ll notice that they work with just the active child window, not any of the others.

Also, you’ll notice that the Save item on the File menu now enables and disables based on whether there are any child windows open, and calls the Save() method on the active child window when it’s clicked.

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

311

The Context Menu Control

The ContextMenuStrip control works identically to a standard MenuStrip control but has some visual differences in the designer.

When you drop a ContextMenuStrip control onto a form, the form goes into menu edit mode just as with a standard menu. However, you can’t add top-level menu items (see Figure 11-23).

Figure 11-23. The context menu strip lets you add only a single list of items.

In addition, because figuring out which context menu you are editing items for can be quite confusing if you have more than one context menu on a form, the menu item comes with a smart tag for building the menu. Just click the tag and click Edit Items to be presented with the menu items editor shown in Figure 11-24.

Figure 11-24. The menu items editor is accessed by clicking Edit Items on the context menu’s

smart tag.

312 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

In the dialog you just choose the type of item you want to add to the menu, by using the drop-down at the top, and then click the Add button to add it into the menu. You set up the actual text of each menu item you add, as well any other properties you want to alter, by using the properties list on the right side of the dialog.

When you’re finished editing, clicking OK takes you out of the editor.

To get a context menu to display itself, just click on the control that you want the menu to attach to, and set its ContextMenuStrip property to the name of the context strip you just created. With that done, when the user right-clicks on the control at runtime, the context menu appears, as in Figure 11-25.

Figure 11-25. All you need to do to enable a context menu is set the ContextMenuStrip property of a control to the name of the context strip itself.

Toolbars and Status Bars

In earlier versions of .NET, menus were one thing, toolbars were another, and status bars were some odd little bolt-on piece of similarly incompatible technology. Thankfully, times have changed. In .NET 2.0, and of course Visual Basic 2005 Express, they are all compatible. If you know how to develop and work with a menu, you also know how to produce a toolbar, and also how to manage a status bar. This makes your life a lot easier in that you have a much shallower learning curve to climb, and it makes my job easier in that I don’t have to type so much.

A toolbar provides buttons at the top of a window to allow quick one-click access to menu items and program options. A status bar, on the other hand, usually lives at the bottom of a window and typically provides feedback on just what a program is currently up to. I say “usually” and “typically” because it’s really up to you, the developer, to decide where you want these controls to live on your windows (although at runtime, there’s nothing stopping the user from moving them around). As with all UI things, though, it really does make sense to stick to standards unless you have a good reason not to, in order to make life easier on users getting familiar with your program.

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

313

After you add a toolbar and status bar to a form, adding elements to them works in a similar fashion to building up a menu (see Figure 11-26).

Figure 11-26. Adding a status strip and tool strip to a form transforms its look quite considerably.

Clicking on either control in design mode brings up a dummy drop-down button that you can click to add elements to the strip, as you can see in Figure 11-27.

Figure 11-27. Click the dummy button on each control to get a menu of things to add to the strips.

On the whole, the items in the list are self-explanatory. However, on the tool strip two items often cause confusion: the DropDownButton and the SplitButton. If you add both to a tool strip and use the Image property to set up graphics for them, you’ll find that they both look identical (see Figure 11-28).

314 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

Figure 11-28. The DropDownButton and SplitButton can be confusing because they look so similar.

Both controls provide a drop-down menu for the user to choose from at runtime. The only difference is that a SplitButton also provides a clickable button. If the user wants to see the menu attached to a split button, the user needs to click the down arrow next to the button. Clicking the button itself triggers a Click event, as usual. Conversely, a drop-down button when clicked always shows the drop-down list of items.

Summary

You’re now pretty much all set to start developing applications with awesome user interfaces. Sure, there are things that we haven’t covered yet, but the basics are all there now that you know how to work with menus, context menus, toolbars, and status bars.

C H A P T E R 1 2

■ ■ ■

Events

Now that you’ve had a taste of developing applications with graphical user interfaces, you may have noticed something quite important: events are everywhere. Unless you want to develop an application with a pretty user interface that does absolutely nothing, you have to work with events. You need to write code to respond to those button clicks, more code to respond to users selecting things in lists, more code to hook into text boxes and even window events. There is just no escaping events if you want to write applications for a modern operating system such as Windows.

So far, writing code for event handlers has been really simple. You either double-click a control on a form to drop into its default event handler, or you select the control in question and then use the Properties window to find the specific event that you are after. When you do that, though, Visual Basic 2005 Express writes code for you, out of sight and out of mind, that connects your event methods to the correct parts of the selected controls. The beauty of this is that although you may not have had an urge to look behind the scenes at just what’s going on, after you do, a whole universe of possibilities for your code opens up.

You see, events behind the scenes are actually very easy to work with. It’s a relative nobrainer to manually write code that connects your own methods to events, and it’s only a tiny step beyond no-brainer to write code that raises events.

Think about that for a second. You can write code that raises events. You may have a complex object, for example, that’s displayed simultaneously in a few windows in your application. Wouldn’t it be great if the object itself could raise an event, just as a control does, that the windows in your application can respond to in order to redraw themselves?

That’s exactly what you’re going to look at in this short chapter.

Hooking Events by Hand

Let’s take a glimpse behind the scenes within a simple Windows application. This isn’t going to be a “Try It Out” in the traditional sense, but feel free to follow along with me to get your feet wet.

Let’s say you have a simple WinForms project as in Figure 12-1.

315

316

C H A P T E R 1 2 E V E N T S

Figure 12-1. Just about the simplest WinForms project you could possibly have

As you already saw a while ago, there’s a source file hidden out of sight that forms part of the Partial class for Form1. You can see it by clicking the Show All Files button on the toolbar at the top of the Solution Explorer, in which case the Solution Explorer changes to look like Figure 12-2.

Figure 12-2. Clicking the Show All Files button shows the partial class source file behind

Form1.

C H A P T E R 1 2 E V E N T S

317

When you add controls to a form, VB Express puts code into this file that sets up those controls based on their size and location, as well as any other property values you set. For example, dropping a button onto Form1 generates this:

<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _ Partial Class Form1

Inherits System.Windows.Forms.Form

'Form overrides dispose to clean up the component list. <System.Diagnostics.DebuggerNonUserCode()> _

Protected Overrides Sub Dispose(ByVal disposing As Boolean) If disposing AndAlso components IsNot Nothing Then

components.Dispose() End If MyBase.Dispose(disposing)

End Sub

'Required by the Windows Form Designer

Private components As System.ComponentModel.IContainer

'NOTE: The following procedure is required by the Windows Form Designer 'It can be modified using the Windows Form Designer.

'Do not modify it using the code editor. <System.Diagnostics.DebuggerStepThrough()> _ Private Sub InitializeComponent()

Me.Button1 = New System.Windows.Forms.Button Me.SuspendLayout()

'

'Button1

'

Me.Button1.Location = New System.Drawing.Point(104, 116) Me.Button1.Name = "Button1"

Me.Button1.Size = New System.Drawing.Size(75, 23) Me.Button1.TabIndex = 0

Me.Button1.Text = "Button1" Me.Button1.UseVisualStyleBackColor = True

'

'Form1

'

318

C H A P T E R 1 2 E V E N T S

Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)

Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font

Me.ClientSize = New System.Drawing.Size(292, 266)

Me.Controls.Add(Me.Button1)

Me.Name = "Form1"

Me.Text = "Form1"

Me.ResumeLayout(False)

End Sub

Friend WithEvents Button1 As System.Windows.Forms.Button

End Class

Notice the commented section labeled 'Button1. Following that comment is the code that sets up the button’s size, location, name, and text properties. Notice also the very last line of code:

Friend WithEvents Button1 As System.Windows.Forms.Button

The key here is the WithEvents keyword. When you declare an object WithEvents, you are effectively telling Visual Basic that you are aware that this object raises events, and you intend to handle some or all of them.

If you were to double-click the button on the form, the event handler that appears in your form’s code looks like this:

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

ByVal e As System.EventArgs) Handles Button1.Click

End Sub

You’ve seen this before. Look closely and you’ll see that this relatively innocent-looking subroutine is suffixed with Handles Button1.Click. Because our Button control was created in the Partial class with the WithEvents keyword, you can use the Handles keyword to automatically set up which methods in your code “handle” events from the button. The name of the subroutine could be anything you want it to be, because it’s the Handles statement that actually hooks the subroutine into a specific event of a specific control. By default, VB Express names event handlers as Controlname_Eventname. So, it follows then that if you wanted to manually set up an event handler, all you’d have to do is add the word Handles to the end of a method name. Realistically though, this is a pain. The subroutines you create must have the exact same signature as the event needs, so if you want

C H A P T E R 1 2 E V E N T S

319

to hook up events in code before runtime, it really is best to do so by using the Properties window as we’ve done in every example in this book.

But what if you wanted to dynamically set up event handlers at runtime? What about creating your own events from scratch? Let’s dig a little deeper.

Creating Custom Events

Time to refer to the online help. First, take a look at the online help for the Button’s Click event (see Figure 12-3).

Figure 12-3. The online help for the Button’s Click event

There are two very interesting items here. First, there’s a new VB keyword that we’ll come back to in a moment: Event. Second, notice that the help says this event thing is of type EventHandler. If you click on that to follow the help down to EventHandler, you get Figure 12-4.