During this hour you will learn
This lesson improves on your programming skills by teaching you ways to improve the usability of your applications. The Timer control lets you generate responses to the internal computer clock. You'll be able to write code that executes after a certain amount of time passes and use the Timer control to perform background processing.
To brighten up your applications, you can add toolbars. Toolbars not only make your applications look more professional, but also give your users additional ways to execute commands. You can paint your toolbar buttons with graphic icons.
Finally, this lesson finishes by explaining how to incorporate pop-up menus into your application. If you embed one or more pop-up menus, your users can perform context-sensitive operations depending on the object they right-click.
FAST TRACK |
Toolbars have been around for a long time. If you've already mastered toolbars and want to learn a topic that is new to Visual Basic 5, jump to Hour 26, "Using Form Templates", to learn about the form template wizard access that comes with Visual Basic 5. |
One event that users don't trigger is a timer event. Your computer's internal clock ticks off 18 beats a second. The clock is vital to the workings of your CPU and memory, and the clock helps synchronize all the hardware and software interaction that must take place.
Fortunately, you can take advantage of these clock ticks. Your Visual Basic application can respond to the clock. You can set up a preset interval of time, after which Windows sends an event message to your application. As with all events, you can write event procedures that execute each time the timer event takes place. The bottom line is that you can write code that executes whenever a fixed amount of time passes.
When you place Visual Basic's Timer control on a form, you set up the time interval that determines the frequency of timer events. That time interval is one of the Timer control's properties. When the interval of time passes, the Timer control triggers the event procedure that you've set up to handle the timer events.
You can add multiple Timer controls to your application just as you can add several instances of the other controls. Therefore, your application can perform an event procedure every minute, every half an hour, and every hour (as might be required of a time and billing application) if you send three Timer controls to the application's form and set up the three intervals.
![]()
This topic section explains how to use the Timer control to write code that responds to time passing. After you learn the Timer control, you'll have learned all of Visual Basic's standard tools (called the intrinsic controls) that appear in the Toolbox. Although you can add more tools to the Toolbox, the intrinsic tools are the ones you'll use most frequently. Therefore, you will have mastered the basics of Visual Basic after you master the Timer control.
Multiple Toolbox Controls You've now seen three kinds of controls: the intrinsic controls that appear in the Toolbox, the insertable object controls such as the Excel control you added to the Toolbox in Hour 20, and ActiveX controls, such as the Common Dialog Box control you added in Hour 17. (All three Visual Basic editions contain extra ActiveX controls, but you can't work with ActiveX inside your code-except for the ActiveX controls in the Toolbox-unless you use the Professional or Enterprise editions.)
When you need to add controls to the Toolbox, use the
Project menu's Components command as you did in Hour 17 when you added the Slider control. If you add third-party controls to VB, you'll add those extra controls to the Toolbox by using theProject menu's Components command as well. Don't add more controls than you need for the current project, however, to keep your application file sizes small.
You'll think of many uses for the Timer control as you become more familiar with it. For example, you can use timer event procedures to perform background processing. Also, you can animate graphics by redrawing the graphic image every time your preset timer event occurs, such as every half a second.
![]()
The best way to place a Timer control on your form is to double-click the Timer control and move the control that appears on the form out of the way of the other objects. You can't resize a Timer control, and it doesn't appear on your form at runtime.
You've already seen another control that you could neither resize nor see at runtime: the Common Dialog Box control (Hour 17, "Adding Control Containers: Dialog Boxes").
![]()
Figure 23.1 shows a Timer control placed in the center of a new form.
You can move a Timer control around on the form, but you can't resize it.
The Timer control supports very few properties. Of the six design-time properties you can set, five aren't particularly unique:
If you set the Timer control's Enabled property to False at design time, the Timer control won't begin responding to events until your code later sets Enabled to True.
![]()
The only property critical and truly unique to the Timer control is the Interval property. The Interval property determines the frequency with which you want the Timer control to generate events. You'll enter (at design time or runtime) the number of milliseconds that have to pass before the Timer control responds to an event. For example, if you set the Interval property to a value of 1000, the timer events will occur every 1,000 milliseconds, or roughly once per second.
The Timer control seems to have some drawbacks at first. The Interval property can hold values only from 0 to 64,767. Therefore, you can set a time interval that spans only about 65 seconds and no more. If you need to set an event interval greater than 65 seconds, you simply can't do so. However, in the Timer control's event procedure (described in the next section), you can ignore events and return to the application without responding to the event until a certain amount of time passes. In other words, although the event procedure you've set up for the Timer control might trigger every 60 seconds, you can place code at the top of the event procedure to return to the application and not respond to the event unless a fixed amount of time has passed (such as an hour or whatever) since the previous execution of the event procedure.
The Timer control isn't actually extremely accurate. Although the crystal inside your computer's clock is highly accurate, by the time Windows sends a timer event to your application, some accuracy is lost. Also, other events that occur can slow down the timer, such as a network access or modem update. Your computer can't do two things at once, and a Timer control inside a running Visual Basic application doesn't always get high priority. Therefore, the Timer control works well when time sensitivity is important to the nearest second, but no control exists in Visual Basic that provides higher precision.
![]()
The Timer control supports only a single event: the Timer event. Therefore, if you name a Timer control tmrClock, you'll write only a single event procedure for the Timer control, named tmrClock_Timer(). Therefore, you'll put the code inside tmrClock_Timer() that you want Visual Basic to execute once every time interval that passes.
Follow these steps to create a simple application that demonstrates the Timer control:
The application is almost finished.
Private Sub tmrTime1_Timer() ' Add one to the display txtTime1.Text = txtTime1.Text + 1 End Sub
Private Sub tmrTime2_Timer() ' Add one to the display txtTime2.Text = txtTime2.Text + 1 End Sub
The two timers update at different times.
In the next lesson, you'll learn how to create and display simple line graphics. You can use the Timer control to animate graphics. Although you have yet to master Visual Basic's graphics components, you can try your hand at animating Picture Box controls with the timer. Animated pictures are more fun to watch than two numbers updating every half a second and every second.
This example incorporates a Picture Box control in a form. In this example, the Timer control manipulates the picture to make it appear and disappear, and then animates the picture. Follow these steps:
Private Sub tmrAni_Timer() ' Turn the picture either on or off If picAni.Visible = True Then picAni.Visible = False Else picAni.Visible = True End If End Sub
The timer and envelope icon are placed on the form.
If you run the application, you'll find that the envelope disappears for one second and then appears the next second. This process continues until you stop the program.
Now that you have the basics down, complicate the project somewhat by animating the opening and closing of the envelope in alternating seconds. To do this, you need to create a Picture Box control array and name the two new pictures picAni2(0) and picAni2(l).
Hour 20, "Understanding Classes and Using the Object Browser," explained what control arrays are. As a review, to create the control array, create the two controls for the array and name them the same, picAni2. (You can also place one Picture Box control and then copy and paste the control to a second occurrence on the form.) VB asks whether you intend to make the controls a control array. If you answer Yes, the new control is assigned an Index property value that's different from the other members of that array. The control is then referenced by the name and the Index property combined, and the Index property acts like a subscript.
![]()
The Picture Box controls will contain the individual cells of the animation. Set the Picture property of picAni2(0) to the same picture as the first icon, Mail01a.ico. Set the Picture property of picAni2(1) to the icon named Mail01b.ico located in the same directory. Now, set both picture boxes' Visible property to False. Set both picture boxes' BorderStyle property to 0 - None. Move the controls to the positions shown in Figure 23.5.
All the animation icons now reside on the form.
Switch the code in the tmrAni_Timer() event procedure with this code:
Private Sub tmrAni_Timer() ' Determine the correct picture to display If intCounter = 1 Then picAni.Picture = picAni2(1).Picture intCounter = 0 Else picAni.Picture = picAni2(0).Picture intCounter = 1 End If End Sub
Declare the integer variable named intCounter in the form module's Declaration section. The counter variable is to "remember" which icon was last displayed so that the other icon can display on the next iteration. The program now causes the timer and the two picAni controls to disappear and the envelope icon to open and close in a very simple animation.
Although it's great to have a timer that runs continuously, it would be better for some applications to start and stop the timer according to user input. Visual Basic has provided a way to do exactly that with the Enabled property. When the Enabled property is set to True, the timer's event procedure executes just as you've seen. When Enabled is set to False, no timer event procedure can execute for that timer.
Add a command button to the application and call it cmdAni. Set its caption to Animate, and then add the following code to the Click event procedure for this button:
Private Sub cmdAni_Click() ' Use the command button to control the animation If intCounter2 = 0 Then cmdAni.Caption = "Stop" tmrAni.Enabled = True intCounter2 = 1 Else cmdAni.Caption = "Animate" tmrAni.Enabled = False intCounter2 = 0 End If End Sub
From the Properties window, set the Enabled property on tmrAni to False. Also, add the variable named intCounter2 to the form's Declarations section. After you move the command button, your form should look something like Figure 23.6.
The form now contains the starting command button.
Run the program to see what happens. The envelope sits still until you click the Animate command button. When you click the button, the animation starts and the caption on the command button changes to Stop. When you then click the Stop command button, the animation stops. If you click the button again (when the command button reads Animate), the motion begins again.
You're probably already thinking of a new video game that uses these techniques. You can build on this application's fundamental animation principles to create moving objects by changing their form locations each timer event.
Toolbars give users one-button access to several common application features. Most often, the toolbar buttons provide the same functionality as menu commands. You can use several different methods to add toolbars to your application. Add toolbars so that your users can quickly access the most important and common menu commands without opening a menu. Toolbars require that you first set up a list of the toolbar button icons by using the Image List control. This topic section explains one of the most common methods.
Several vendors provide Visual Basic custom controls (get the ActiveX-compatible ones) that supply toolbars. VB's Professional and Enterprise editions supply the Toolbar control inside the ActiveX custom control named Microsoft Windows Common Controls 5.0. Press Ctrl+T and select this control to add the control to your Toolbox. Figure 23.7 shows the Toolbar control that appears (other new tools appear, as well).
If you use VB's Standard edition, you don't have this control. Check out online services for custom toolbar controls you may be able to download for free (make sure that they don't end in the older .VBX file extension) or for a small charge. Although you can manually create toolbars with the Standard edition, doing so is painstaking and you'll be glad you found a control to do the dirty work. Creating a toolbar manually without a Toolbar control requires that you place a wide Picture Box control on the form the size of the toolbar (the toolbar area generally spans an entire ribbon across the form) and then add command buttons that do the job you want done. The command buttons should use the Picture property to hold the toolbar button's icon. Each command button will then have its own Click() event procedure that performs the work.The Toolbox now contains the Toolbar control.
After you add the Toolbar control to your Toolbox, adding a toolbar to your application is simple. You'll add the toolbar to the top of your primary Form window. If you write MDI applications, you can add toolbars to one or more forms within the project. This topic explains how to add a toolbar to your Form window and connect the toolbar buttons to their event procedure code.
You can easily add a toolbar to the top of the animated envelope application you created at the end of the last topic section. Open the application, display the Form window, and double-click the Toolbar control to add the toolbar to the top of the form. The toolbar doesn't show up well yet because you've not added buttons to the toolbar. If you have the grid turned on, you'll see the toolbar at the top of the form because the toolbar covers up the grid dots.
You can't adjust the toolbar's size with the mouse or by changing the Left, Top, or Width property settings. The toolbar will consume the entire area across the top of the form. If you adjust the form, the toolbar automatically adjusts with the form. (The toolbar's Width property always matches the form's Width property.)
![]()
You can change the toolbar's Align property value to vbAlignBottom so that the toolbar rests on the bottom of the Form window. The standard location for toolbars, however, is at the top of the form or directly beneath a menu bar if the form uses a menu. In most cases, you should stay with the standard so that your users have no troubles adapting to your application's features.
Adjusting the Toolbar Settings
The Toolbar control provides some unusual property values that you haven't seen with the standard intrinsic controls. For example, the Toolbar control supports the About property. When you click the About ellipses, a small dialog box opens that describes the control's copyright information. When you insert a control, the control's vendor (in this case, Microsoft) often includes copyright information about the control, so you'll always be able to determine the source.
When you click the Custom property's ellipses, the dialog box in Figure 23.8 appears and makes it easier to set the remaining property settings. Rather than use the Properties window to set up toolbars, most programmers prefer the Custom property's dialog box. Therefore, you'll also probably want to use this dialog box to set up the toolbar.
Toolbar properties are easier to set in the Property Pages dialog box.
As you set various properties inside the Property Pages dialog box, you can click the
Apply button to see the results of your choices. For example, if you change the toolbar'sBorderStyle to 1 - ccFixedSingle and then clickApply, the dialog box remains on-screen but the border appears around the toolbar on the Form window in the background.![]()
Most toolbar buttons display graphic icon images. Although you can set up toolbar buttons to display captions, a picture is worth a thousand words, especially because virtually every toolbar in every Windows program displays buttons without captions. The buttons that use picture icons require that you add another new control to your Form window. That control, found on the same insertable set of controls that contains the Toolbar control, is called the Image List control, which holds a series of one or more images. The Image List control does not display these images, but merely holds the image list for other controls that need such a list as your toolbar will need for its buttons.
The Image List control acts somewhat like the Timer control in that the Image List control never shows up on the form when you run the application. The Image List control is a container for the toolbar icons. Therefore, when you place the Image List control on your form, move the Image List control away from the other controls. After you load the Image List control with icons (as explained in the example at the end of this topic), you then can link each toolbar button to each icon in the Image List control.
Here are the general guidelines to follow when creating the toolbar:
The example at the end of this topic section demonstrates toolbar creation.
If your toolbar button mimics one of the menu commands, the rest
of your programming job is simple. An event procedure can trigger
another event procedure simply by calling that event procedure
just as it would any other procedure. For example, if a Open toolbar
button is to mimic your application's File menu's Open
command, the following statement is the only one needed inside
that toolbar button's event procedure (assuming that you named
the File menu's Open option mnuFileOpen):
Call mnuFileOpen.Click ' Trigger the menu command
Remember that you don't include the parentheses when using Call if the called procedure requires no arguments.
![]()
The toolbar's most important event procedure is ButtonClick(). Unlike command buttons that support the Click() event procedure, toolbars support their own unique event procedure, ButtonClick(). You'll have to code ButtonClick() to respond to a user's toolbar click. The ButtonClick() procedure is one of the few event procedures that requires arguments. Your event procedure will have to check ButtonClick()'s argument to determine which toolbar button the user clicked.
With the first topic section's animation application still open, follow these steps to add a toolbar to the form:
The images are ready for the three toolbar buttons you'll add.
You can add multiple toolbars to your application and adjust their visibility by setting each one's Visible property to True or False to show or hide them as needed. Multiple toolbars that appear at the same time appear beneath one another.
![]()
You've now added three toolbar buttons and placed images on them. Your final job is to connect proper event-procedure code to the buttons so that they respond properly.
Double-click the toolbar to open the tlbAni_ButtonClick() event procedure. Notice that the parentheses includes an argument. This argument, Button, passes as the toolbar button the user clicked to generate this event. You can use the button's Index property to respond to the correct button. Listing 23.1 shows the event procedure that turns on the animation if users click the first button, turns off the animation if users click the second, and stops the running program if users click the third.
Listing 23.1 Tlbutton.bas: Connecting Actions to Toolbar Buttons with the Index Property
Private Sub tlbAni_ButtonClick(ByVal Button As ComctlLib.Button) ' Respond to the correct toolbar button Select Case Button.Index Case 1: tmrAni.Enabled = True ' Turn on animation cmdAni.Caption = "Stop" Case 2: tmrAni.Enabled = False ' Turn off animation cmdAni.Caption = "Animate" Case 3: End End Select End Sub
Run the application to see the toolbar in Figure 23.10. You now can click the red light and green light toolbar buttons or the Animate command button to start and stop the animation. You also can terminate the program by clicking the Stop toolbar button.
The toolbar gives users extra control.
When placing toolbars, you may want to take advantage of some of the extra features available with the control. Two of the features are incredibly easy to implement and add professionalism to your application.
A ToolTip is a pop-up description that appears when you
let your mouse pointer hover over a button or other object. If
you move your mouse pointer to VB's toolbar icon that resembles
a diskette, the ToolTip that appears (after a brief pause) will
read Save Project. To add ToolTips to your toolbar buttons, open
the Toolbar control's Property Pages dialog box and click the
Buttons tab; then, in the ToolTipText text box, enter the
pop-up description that you want your users to see as a ToolTip.
For example, you could add the description Start Animation to
the first toolbar button's ToolTip. Click the Index button
to switch to the next toolbar button and add ToolTips text for
it, and then do the same for the third button. When you subsequently
run the application, your ToolTip automatically appears when you
place your mouse pointer over a button.
You'll learn more about applying ToolTips to other controls in Hour 29, "Building a Help Subsystem."
![]()
Figure 23.11 shows a pop-up menu (sometimes called a context menu). When users right-click the form, the pop-up menu can appear. Your applications can contain several pop-up menus that appear depending on where users right-click.
A pop-up menu is there when your users need it.
You'll create the menu that appears in a pop-up menu just as you create regular menus that appear at the top of some application's menu bars. The PopupMenu method provides the control that initiates the pop-up menu. Therefore, you use the Menu Editor to create the menu that appears at the user's right-click.
When creating pop-up menus, you must make sure that you create a regular menu item that contains at least one submenu. The submenu is the menu that appears when users right-click. Figure 23.12 shows the Menu Editor with the pop-up menu from Figure 23.11 defined.
The Menu Editor creates the pop-up menus.
While looking at Figure 23.12, consider the following points:
You must decide where you want the pop-up menu to appear. For example, you can create multiple pop-up menus (as long as the top menu level has a different name) and pop one up if users right-click a command button, pop another up if users right-click a form, and pop another up if users right-click over a label.
Load the toolbar example you created at the end of the previous
topic section, and then press Ctrl+E to display the Menu Editor.
Enter the values shown earlier in Figure 23.12. Name the three
submenu options mnuAni, mnuStop, and mnuExit. The menu name is
mnu because the top level's name is mnu. It's vital that you deselect
the Visible check box so that the menu doesn't appear at
the top of the form.
Open the Code window (choose Code from the View
menu). Enter a new event procedure that contains the following
code (if you select Form and MouseUp from the Code window's two
drop-down lists, VB writes the first and last lines for you):
Private Sub Form_MouseUp(Button As Integer, Shift As Integer, [ccc]X As Single, Y As Single) If Button = 2 Then Form1.PopupMenu mnu End If End Sub
Generally, you'll insert the pop-up menu code inside the MouseUp event for whatever object you want to use for the pop-up trigger. This example assumes that the pop-up menu will appear when users right-click the form. (No example in this lesson renamed the form from Form1.) The Button argument contains 2 if the right mouse button caused this event (you can ignore the remaining arguments for this example). If the Button argument is a 2, apply the PopupMenu method to the form and designate the top-level name of the menu you want to display at the pointer. In this example, you've defined only one menu, mnu.
If code follows the PopupMenu method, the code doesn't execute until users finish with the menu.
![]()
You'll have to write the event procedures for the menu options as you need to do with a regular menu. Therefore, the event procedures in Listing 23.2 take care of the menu selections.
Listing 23.2 Menuopts.bas: Adding Code for Pop-Up Menu Options
Private Sub mnuAni_Click() ' The user clicked the Animate menu item tmrAni.Enabled = True cmdAni.Caption = "Stop" End Sub Private Sub mnuExit_Click() ' The user clicked the Exit menu item End End Sub Private Sub mnuStop_Click() ' The user clicked the Stop Animation menu item tmrAni.Enabled = False cmdAni.Caption = "Animate" End Sub
Adding a pop-up menu to another object is just as easy. In the
Menu Editor, create another menu option. To do so, open the Menu
Editor and click the last item in the menu (in this case, the
E&xit item). Click the Next button to add another menu.
Click the left arrow to make the new menu item another high-level
item and enter mnu2 in the Caption and Name text
boxes. Be sure to deselect the Visible check box.
Enter two more items subordinate to mnu2. Enter &Hide Toolbar
for the first Caption and mnu2Hide for the Name.
Enter &Display Toolbar and mnu2Display for the Caption
and Name text boxes. Click OK to close the Menu Editor.
Enter the following MouseUp event procedure for the toolbar:
Private Sub tlbAni_MouseUp(Button As Integer, Shift As Integer, [ccc]x As Single, y As Single) If Button = 2 Then Form1.PopupMenu mnu2 End If End Sub
Your only job now is to add the menu option code. Type the following event procedures to display and hide the toolbar in response to the pop-up menu:
Private Sub mnu2Display_Click() ' Display the toolbar tlbAni.Visible = True End Sub Private Sub mnu2Hide_Click() ' Hide the Toolbar tlbAni.Visible = False End Sub
Hiding a toolbar makes the toolbar unable to generate a response to a mouse click.
![]()
If you run the program, you now can display two pop-up menus. If you right-click the form, you get the menu that turns the animation on and off. If you right-click the toolbar, you get the menu that hides and displays the toolbar.
The application has a problem, however; if you turn off the toolbar, you can never turn it back on again! This demonstrates that a toolbar and pop-up menus should never take the place of a regular menu bar. The regular menu bar can contain options that hide and display the toolbar (perhaps with a check mark if the toolbar shows), as well as options that turn the animation on and off.
This lesson explained how to use the Timer control to add time-sensitive processing to your applications. The Timer control keeps track of the milliseconds that pass and triggers an event when a preset amount of time goes by. The Timer control supports only one event, so your programming is relatively light when using the control.
The Toolbar control adds another dimension for your users. Toolbars give your application one-button access to the most common controls. Before you can place icons on toolbar buttons, however, you must insert those icons inside the Image List control.
You now can give your users another way to issue commands besides the menu bar and toolbar. With pop-up menus, your users can right-click certain objects to display a pop-up menu. You'll want to create pop-up menus that help users do what's most common on the object they right-click.
In the next hour, "Shaping Up Your Applications with Graphics," you'll learn how to place graphics on the Form window.