During this hour you will learn
This hour's lesson explores more controls in the Toolbox, so you can expand your Visual Basic knowledge and begin to add these new controls to your applications. You'll see that manipulating new controls doesn't require many additional programming skills, because all VB controls support a set of properties that you can set at design time with the Properties window or at runtime with code. Some controls do require extra coding, but that coding generally only initializes and manages the control.
Many times, Visual Basic adds scroll bars to your applications for you. For example, when you programmed multiline text boxes in Hour 4, "Activating Controls," Visual Basic displayed a horizontal or vertical scroll bar (or both) if the multiline text box wasn't large enough to display all the text. In addition to the automatic scroll bars that appear when necessary, you can place vertical and horizontal scroll bars anywhere on your forms when you want to give users more control over a list, volume, or position within a document.
FAST TRACK |
Do you want to scroll past scroll bars? If you already know how to program them or want to return to them later, you can jump to the next topic section, "The Picture Box Control", to learn the advantages and disadvantages of using a picture box control instead of an image control. (On your way to the next topic section, check out this topic's "Next Step" section on if you want to learn about the slider control.) |
Scroll bars allow users to shift their position within a text area, a graphic, or any of a number of other form objects. Unlike the built-in scroll bars that automatically appear-such as those on the multiline text box shown in Figure 18.1-you must carefully control the scroll bars that you choose to place on the form.
Visual Basic controls automatic scroll bars such as these.
Visual Basic offers the vertical scroll bar and horizontal scroll bar individually because you won't always want to place both of them on the form at the same time.
![]()
The scroll bars that you place on your forms conform to the Windows 95 standard that automatically adjusts the size of the scroll bar's thumb (the moving bar inside the scroll bar shaft) to display the relative size of the scrolling area. The thumb is small when the scroll range is large to show your users that the scroll bar controls many values; the thumb is large when the scroll range is small to show your users that the scroll bar controls only a few values.
When you place scroll bars on your form, you'll be most concerned with setting the scroll bar properties described in Table 18.1.
Table 18.1 Important Scroll Bar Properties
Property | Description |
LargeChange | The amount the scroll bar changes when users click the scroll bar on either side of the thumb (if you were scrolling text, for example, LargeChange might scroll a full screen) |
Max | The maximum value returned from the scroll bar when users scroll the scroll bar to its most extreme position (the far right for horizontal scroll bars and the bottom for vertical scroll bars) |
Min | Specifies the minimum value returned from the scroll bar when users scroll the scroll bar to its least extreme position (the far left for horizontal scroll bars and the top for vertical scroll bars) |
SmallChange | The amount the scroll bar changes when users click a scroll bar arrow to move the thumb either direction (if you were scrolling text, for example, SmallChange might scroll a single line) |
Value | The scroll bar's current value, bounded by the Min and Max properties as well as the increment |
As you can see from Table 18.1, a scroll bar is a general-purpose control that returns values based on minimum and maximum values. For example, you can issue a scroll bar that steps through (as users scroll) the returned values 1 through 1,000 with a LargeChange increment of 25, steps through the returned values 100 through 200 with a LargeChange increment of 1, or steps through the returned values 1,000 through 32,000 with a LargeChange increment of 5,000. In other words, you can control all aspects of the scroll bar's returned value range and increment by setting the appropriate properties at design time or runtime.
The scroll bar can return only positive integer values (from 1 to 32,767), so you can't increment or set maximum and minimum fractional values. If the scroll bar is to select fractional values, you have to apply an appropriate calculation to the scroll bar's Value property to convert the integer value to a fractional value.
![]()
You can set the height and width of a scroll bar at design time or runtime. The scroll bar's default thickness is a standard Windows size, and you'll generally want only to adjust the length.
Scroll bars allow you to pan across graphic images. When you pan across a large picture, only a portion of the picture appears at any one time. Although scroll bars themselves don't do anything to the graphic display, you can use the scroll bar values to adjust images.
To experience one panning method, create a new project and adjust the form's Width and Height measurements to 7,155 and 5,535 respectively. Add a frame control that takes the entire form, but leave enough room at the right and below the frame for vertical and horizontal scroll bars (make the frame's Caption property blank).
Add the vertical and horizontal scroll bars (named vsbMoney and hsbMoney). Set the vsbMoney.Min property to 850 and the hsbMoney.Max property to 1200. Set each scroll bar's LargeChange property to 50. Your form window should look something like the one shown in Figure 18.2.
You can create a control that pans the window.
Now add an image control named imgMoney to the frame. To place the image on the frame, double-click the image control to place an image on the form, cut the image, and then paste the image back onto the frame area. This seems redundant, but you want to ensure that Visual Basic considers the image part of the frame. Expand the image to the size of the frame.
Set the image's Picture property to this file in your VB directory: \Graphics\Metafile\Business\Dollar.WMF. The .WMF extension indicates that the file is a Windows metafile, meaning that you can enlarge the image to a width of 12,000 twips and a width of 8,500 twips. (A twip is a Windows pixel measurement that is a twentieth of a pixel.) The dollar bill won't completely fit within the frame's width (this is good). Move the image so that you see only the right edge of the bill. Users will pan the bill into view at runtime.
Name the Image control imgMoney. Figure 18.3 shows how your screen should look.
The form window now includes the image.
Add the following two event procedures that adjust the image's area when users change a scroll bar:
Private Sub vsbMoney_change() imgMoney.Top = vsbMoney.Value * 10 End Sub Private Sub hsbMoney_Change() imgMoney.Left = hsbMoney.Value * 10 End Sub
When you run the application, the first time you scroll the image to the right with the horizontal scroll bar, the bill comes into view. The bill moves up and out of the way when you click the vertical scroll bar. Due to the image's original negative Left property value (because you moved the image so that only the right edge showed), the horizontal scroll bar doesn't put the image back where it first appeared but instead places the bill so that its edge touches the left window edge. Through code, you could adjust the scroll bar's Value property to position the bill back at a negative location if you wanted users to be able to scroll the bill off the window as it first appeared.
Several panning methods exist. You can control whether you want to move the application window over an image, or pan an image over an application's window (as is done here). The calculations inside the code handle the panning movement you want.
![]()
If you use Visual Basic Professional Edition, you can add a tool
representing the slider control to your Toolbox. Choose the Components
command from the Project menu and then click the control
set named Microsoft Windows Common Controls 5.0. When you close
the dialog box, your Toolbox will contain new controls (as shown
in Figure 18.4), including the slider control.
The slider control now appears in your Toolbox.
The Slider tool
You must use the Professional or Enterprise Edition of Visual Basic to create this example.
![]()
The slider control works like the horizontal scroll bar control, except that Microsoft recommends using the slider control for user input when the input can span a range of values. For example, if users are to enter a number from 1 to 1,000, you could ask them to enter the number from within an input box, a text box, or with a scroll bar that moves through that range. Microsoft recommends that if you have access to a slider control, you use the slider control for such user input. The slider control displays optional tick marks (through the TickStyle property) that you can control.
To consider the differences between a slider and a scroll bar, start a new project and place a horizontal scroll bar, a slider, a command button (with the Caption property set to E&xit), and two labels on the form, as shown in Figure 18.5.
This form contains a scroll bar, a slider, a command button, and two label controls.
Name the first label lblScroll and set its Font size to 18. Name the second label lblSlide and set its Font size also to 18.
Name the command button cmdExit and complete this Click event procedure in the Code window:
Private Sub cmdExit_Click()
Unload Me ' Unloads the current form and ends program
End Sub
Name the scroll bar hsbScroll and name the slider control sldSlide. Type the following event procedures:
Private Sub Form_Load()
hsbScroll.Max = 150
hsbScroll.Min = 0
hsbScroll.LargeChange = 15
hsbScroll.Value = 50
lblScroll.Caption = hsbScroll.Value
' Now do same for slider
sldSlide.Max = 150
sldSlide.Min = 0
sldSlide.LargeChange = 15
sldSlide.Value = 50
lblSlide.Caption = sldSlide.Value
End Sub
Private Sub hsbScroll_Change()
lblScroll.Caption = hsbScroll.Value
End Sub
Private Sub sldSlide_Change()
lblSlide.Caption = sldSlide.Value
End Sub
Run the application and click the shaft of the scroll bar to see what happens to its position. Then click the scroll bar arrows to study the difference in movement between the large change and small change values. Now, click the slider's line or drag the slider pointer to see how it works. Figure 18.6 shows the running application. You should note that SmallChange has no effect on the slider when used with the mouse, because the slider never has end buttons. The arrow keys, however, will work to move the slider incrementally in small steps when the slider has the focus.
This simple application introduces you to the slider control.
You've already used the image control to place images on the form. The picture box control works almost the same as the image control does, except that the image control isn't as flexible as the picture box control. Also, the picture box control is less efficient than the image control, but today's fast computers should offer no speed problems. The picture box control supports more properties and methods than the image control does.
FAST TRACK |
Are you far beyond displaying simple graphic images on your forms? Do you want more jazz in your applications? Check out the lessons in Part IV, "Adding Power to VB Programs", to find lessons on multimedia and advanced graphics tools. |
This topic section reviews the picture box control and its properties. You'll have no trouble understanding the picture box control now that you've used the image control. The key task you need to master is the LoadPicture() function, which lets you set picture box control images at runtime.
When you need to display a graphic image, you'll select the picture box control or the image control. Both support the same fundamental set of properties, methods, and events, but you'll find that the picture box control offers a better choice of property options. Table 18.2 lists the most important picture box control properties.
Table 18.2 Important Picture Box Properties
Property | Description |
Align | Determines the relative location where the picture appears on the form |
AutoSize | Specifies whether the control is to expand or contract in size to display the entire picture, or whether the picture box control is to display only a portion of the image |
BorderStyle | Draws an optional border around the picture |
FontTransparent | Determines whether background text will show through the image |
Picture | Contains the path and file name of the graphic image |
The picture box control doesn't support the image control's Stretch property that you used in earlier lessons. The picture box control uses the AutoSize property to stretch the underlying control's size to the image being loaded. AutoSize allows this automatic resizing during runtime as you load different pictures into the image.
![]()
You can specify at design time the initial image to be displayed in the picture box control by entering the path and file name in the control's Picture property. Use the built-in LoadPicture() function when you want to display an image or change an image during runtime. Here is the syntax for using LoadPicture():
picPictureCtl.Picture = LoadPicture(strExpression)
You can't directly assign the path and file name of the picture to the Picture property at runtime. You must enclose the path and file name inside the LoadPicture() function's argument. The following assignment statement replaces the picture box control's picture with a new image loaded from the root directory:
Picture1.Picture = LoadPicture("c:\planes.bmp")Table 18.3 lists the graphic file types you can load with the picture box control.
Table 18.3 File Types Supported by the Picture Box Control
Type | Extension |
Bitmap | .BMP |
Graphic Image File | .GIF |
Icon | .ICO |
JPEG | .JPG |
Metafile | .WMF, .EMF |
Create a new project and place a picture box control in the center of the form window. Expand the form to a height of 6,825 and a width of 7,650. Expand the picture box control to a height of 3,540 and a width of 4,020.
Click the ellipsis (...) in the setting area for the picture box control's Picture property, and then select the \Graphics\Metafile\Business\Dollar.WMF file used in the last topic section's example. The bill will appear shrunken (see Figure 18.7) because the picture box control's AutoSize property is set to False.
AutoSize is set to False, so the image appears shrunken.
Change AutoSize to True, and the control immediately expands to the size of the file's image (see Figure 18.8).
When AutoSize is set to True, the image expands.
Change the AutoSize property back to False to see that the image doesn't shrink to its original size. When you set AutoSize to True at design time or runtime, the image's control size increases or decreases to hold the entire image. Therefore, you now have to manually change the Height and Width properties back to 3,540 and 4,020. Name the picture box control picPicture.
Add a command button named cmdChangePic to the previous example's form. Type &Change Picture for the Caption property of the command button. Add the following event procedure for the command button:
Private Sub cmdChangePic_Click()picPicture.Picture = LoadPicture("VB\Graphics\MetaFile\
[ccc]Business\Computer.WMF")
End SubYou have to insert the exact path of your computer's Computer.WMF file in the LoadPicture() function. If the line becomes too long to fit easily in the Code window, you can end the line early with Visual Basic's code-continuation character, an underscore (_) that follows a single space, and then continue it on the next line.
![]()
When you run the program, you see the original dollar image. Click the command button to see the image shown in Figure 18.9.
The picture has changed!
This topic section introduces some new kinds of list boxes. You already know how to work with simple list and combo boxes. You also know how to use the Open and Save dialog boxes. The Toolbox also contains three special list boxes that work with file data.
Visual Basic's three special list boxes help you manage directories, drives, and files. Here are descriptions of these special list boxes:
Figure 18.10 shows a form window that contains all three kinds of special list boxes.
You can work with these three special list boxes.
You might wonder why Visual Basic supplies these file-related controls, because you've already seen the common dialog box control that supports the full use of these controls as a set without requiring you to place the controls individually on a form. Well, these special list controls let you place specific kinds of lists on a form whenever you need just one or two aspects of a file. For example, you might need to write data to users' disks. Although your application will handle the file name and directory, you need to ask the users which disk drive should receive the application's data.
![]()
These lists don't work in tandem with each other unless you program them to do so. For example, if you place the three controls on one form and run the application, changing the disk drive doesn't change the directory or file name shown in the other two controls. If you really want to, of course, you can write event procedures to keep these controls in synch with each other.
![]()
Use the drive list box control to let users select a disk drive. This control is smart enough to search the host computer and determine which drives-local and remote, floppy, hard, and CD-ROM-exist on each user's system. The control then displays these choices graphically when users open the drive list box (see Figure 18.11).
Users can select from the drive list box.
The open drive list box
The drive list box control first displays the drive from which users launched the application, but you can override this default drive by using Visual Basic code to point the control to another drive.
![]()
Use the directory list box control to let users select a directory folder. This control is smart enough to search the host computer and determine which directories exist in the system. The directory list box displays these choices graphically by using the standard Windows format.
Remember that the directory list box control can't determine which drive is selected in the drive list box. You have to take care of linking the drive to the directory, as explained at the end of this topic section.
The directory list box control first displays the directory from which users launched the application, but you can override this default directory by using Visual Basic code to point the control to another directory.
![]()
Use the file list box control to let users select a file. This control is smart enough to search the host computer and determine which files exist in the file system. The file list box then displays these choices graphically by using the standard Windows format.
As with the directory list box control, the file list box control can't determine which drive (or directory) is selected in the drive (or directory) list box. You have to take care of linking the drive to the directory, as explained at the end of this topic section.
The file list box control first displays the files from the directory in which users launched the application, but you can override this default directory by using VB code to point the Directory List Box control to another directory before linking the file list box to the folder.
![]()
Visual Basic supports several drive and directory commands that prepare the file list controls, as described in Table 18.4.
Table 18.4 Drive and Directory Commands
Command | Description |
ChDrive strDrive | Changes the default drive to the drive in the string expression |
ChDir strDirectory | Changes the default directory to the directory in the string expression (if you specify no drive inside the string, Visual Basic selects the directory on the current drive) |
Kill strFileSpec | Erases the file or files (specified with wild cards) specified by the string expression |
MkDir strDirectory | Creates the directory specified by the string expression |
RmDir strDirectory | Erases the directory specified by the string expression |
RmDir produces an error if you try to remove a directory that still contains files.
![]()
In addition to the statements shown in Table 18.4, Visual Basic supports the Dir() function, which checks whether files exist, and the CurDir() function, which returns the name of the current directory.
Suppose that you want to point the drive list box and directory list box controls to the directory C:\MyFiles. You can insert the following code in the Form_Load() procedure: ChDrive "C:" ChDir "\MyFiles"The drive list box, directory list box, and file list box controls now point to the C:\MyFiles directory when they appear on the form, rather than to the application's current directory.
The Dir() function requires a little more explanation. Suppose that you want to know if a file named SALES98.DAT exists in the root directory on drive D. You can check for such a file this way: If (Dir("c:\SALES98.DAT")) = "SALES98.DAT" Then msg = MsgBox ("The file exists") Else msg = MsgBox ("The file does not exist") End IfThe Dir() function returns the file name you pass as an argument. The file name is returned only if that file resides inside the directory argument you provide. If Dir() doesn't return the file name, the file doesn't exist on the drive.
You can pass Dir() a wild-card file specification like this: Dir("c:\Sales*.DAT")Dir() will return the first file found that meets the wild-card specification-if any files meet the specification. After you pass the first file specification, you can make subsequent calls to Dir() by specifying Dir without parentheses or any argument. Visual Basic keeps returning files that match your wild-card file specification until the last file is found. When Dir returns a null string (""), you must include a file specification in the next call to Dir(); otherwise, Dir will return an error.
If you want to set the drive list box control's drive to a specific disk drive, set the control's Drive property this way:
drvDisk.Drive = "d:\"The drive list box control then will display with D: at the top of the list. If users change the drive list box to a different drive, the drive list box's Change() event occurs. You can set the users' selected drive to the default drive with the following statement inside drvDisk_Change():
ChDrive drvDisk.DriveUse the following code to set the Drive property of the directory list box control to the drive the control is to display:
dirDirect.Drive = drvDisk.DriveThis assignment statement sets the directory's drive to the directory selected by the users. You can add the directory list box control's disk assignment to the drvDisk_Change() event procedure.
After users change the directory list box control to a different directory, the control's Change event occurs. In the Change event procedure, you can set the current directory to the users' directory this way: ChDir dirDirect.PathThe directory list box control supports a rather unusual access scheme-it supports a property named ListIndex. The value of ListIndex is -1 for the selected directory, -2 for the directory immediately above the selected one, -3 for the directory immediately above that, and so on. The ListIndex property is 0 for the first subdirectory of the selected directory, 1 for the next subdirectory, and so on.
If you want to display only certain files in the file list box, assign a string file specification as follows to the file list box control's Pattern property: filFiles.Pattern = "*.vbp; *.frm"You can include as many file specifications as you like, indicated with wild cards within the string's quotation marks. The file list box control immediately changes to reflect the new pattern by showing only those files. When users select a file, the file list box control's Change event occurs and the selected file appears in the FileName property. As with the drive list box control, the selected file also appears as the ListIndex value of -1.
After users select a path, you can change the file list box control to reflect files in that path, as follows: filFiles.Path = dirDirect.PathThis lesson explained how to use the scroll bar controls as well as the slider, picture box, and file list controls to add more processing capability to your forms. As you learn more controls, you increase your Visual Basic programming bag of tricks and can add extra I/O capability for your users.
The scroll bar controls give users a way to pan, select, and enter values with the mouse or keyboard. Visual Basic supports horizontal and vertical scroll bars. You can adjust all the scroll bar attributes so that the scroll bars return the values you need when users change the scroll bar. If you use the Professional or Enterprise Edition of Visual Basic, you can offer slider controls so that your users can more easily enter values without the keyboard. The picture box control displays images just like the image control does. Unlike the image control, however, the picture box control adds flexibility so that you can automatically adjust the size of the picture box based on the size of the image you want to display. The last topic section taught you the individual file controls available from the standard Toolbox. Although you almost always will use the File Open and File Save dialog boxes for user control of file selections (the dialog boxes require less programming work), the individual file controls provide a way for you to let users select individual files, directories, or drives when needed. In Hour 19, you'll learn how to integrate the users' printers into your Visual Basic applications.Change the picture box control application you created in the second topic's "Next Step" section to display the File Open dialog box when users want to change the image in the picture box control. When users select a graphic file, display the selected file in the image. Be sure to write the supporting code that sets the default file types to the picture box control's graphic images (from Table 18.3) and that handles the users' click of the Cancel button by keeping the original image in the picture box control. Create a dialog box that mimics the File Open dialog box. Use only drive, directory, and file selection lists as well as OK and Cancel command buttons. Write code so that an application that uses this dialog box will change the directory or file lists whenever users select a different drive or directory.