Tải bản đầy đủ (.pdf) (112 trang)

Visual Basic 6 Black Book phần 4 docx

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (3.37 MB, 112 trang )



Accessing Individual Pixels In A Picture Box
The Testing Department is calling. Wouldnt it be better to let users select new colors in your
SuperDuperTextPro program by just clicking the new color they want in a picture box instead of asking
them to type in new color values? Hmm, you think, how do you do that?
You can use the Point method to determine the color of a pixel in a picture box. This method returns the
red, green, and blue colors in one Long integer.
Lets see an example to make this clear. Here, well let the user click one picture box, Picture1, to set the
color in another, Picture2, using the MouseDown event:

Private Sub Picture1_MouseDown(Button As Integer, Shift As Integer, _
X As Single, Y As Single)

End Sub
When the user clicks a pixel in Picture1, well set the background color of Picture2 to the same color,
and we get that color using the Point method:

Private Sub Picture1_MouseDown(Button As Integer, Shift As Integer, _
X As Single, Y As Single)
Picture2.BackColor = Picture1.Point(X, Y)
End Sub
The result of this code appears in Figure 10.12. When the user clicks a point in the top picture box, the
program sets the background color of the bottom picture box to the same color.
Figure 10.12 Using the Point method to get a points color.
TIP: Besides getting a pixel with the Point method, you can also set individual pixels with the PSet
method. See Drawing Lines And Circles In A Picture Box earlier in this chapter.
Copying Pictures To And Pasting Pictures From The Clipboard
The users love your new graphics program, SuperDuperGraphics4U, but would like to export the images
they create to other programs. How can you do that?
You can copy the images to the Clipboard, letting the user paste them into other programs. To place data


Visual Basic 6 Black Book:Picture Boxes And Image Controls
http://24.19.55.56:8080/temp/ch10\331-334.html (1 of 3) [3/14/2001 1:42:12 AM]
Simpo PDF Merge and Split Unregistered Version -
in the Clipboard, you use SetData(), and to retrieve data from the Clipboard, you use GetData().
An example will make this clearer. Here, well paste a picture from Picture1 to Picture2 using two
buttons: Command1 and Command2. When users click Command1, well copy the picture from
Picture1 to the Clipboard; when they click Command2, well paste the picture to Picture2.
To place the image in Picture1 into the Clipboard, we use SetData():

Clipboard.SetData data, [ format]
Here are the possible values for the format parameter for images:
" vbCFBitmap2; bitmap (.bmp) file
" vbCFMetafile3; metafile (.wmf) file
" vbCFDIB8; device-independent bitmap (.dib) file
" vbCFPalette9; color palette
If you omit the format parameter, Visual Basic will determine the correct format, so well just copy the
picture from Picture1.Picture to the Clipboard this way:

Private Sub Command1_Click()
Clipboard.SetData Picture1.Picture
End Sub
To paste the picture, use GetData():

Clipboard.GetData ([ format])
The format parameter here is the same as for SetData(), and as before, if you dont specify the format,
Visual Basic will determine it. So when the user clicks the second button, we paste the image into
Picture2 this way:

Private Sub Command2_Click()
Picture2.Picture = Clipboard.GetData()

End Sub
Thats all it takes. When you run the program and click the Copy and then the Paste button, the image is
copied to the Clipboard and then pasted into the second picture box, as shown in Figure 10.13. The
program is a success. Now were using the Clipboard with picture boxes.
Figure 10.13 Copying a picture to and pasting it from the Clipboard.
Visual Basic 6 Black Book:Picture Boxes And Image Controls
http://24.19.55.56:8080/temp/ch10\331-334.html (2 of 3) [3/14/2001 1:42:12 AM]
Simpo PDF Merge and Split Unregistered Version -
Stretching And Flipping Images In A Picture Box
You can gain a lot more control over how images are displayed in picture boxes using the PaintPicture
method:

PictureBox.PaintPicture picture, x1, y1, [width1, height1, [x2, y2, _
[width2, height2, [opcode]]]]
Using this method, you can stretch or flip images in a picture box. Heres what the arguments passed to
PaintPicture mean:
" picture The source of the graphic to be drawn onto the object; should be a Picture property.
" x1, y1 Single-precision values indicating the destination coordinates (x-axis and y-axis) on the object
for the picture to be drawn. The ScaleMode property of the object determines the unit of measure used.
" width1 Single-precision value indicating the destination width of the picture. The ScaleMode property
of the object determines the unit of measure used. If the destination width is larger or smaller than the
source width (width2), the picture is stretched or compressed to fit. If omitted, the source width is used.
" height1Single-precision value indicating the destination height of the picture. The ScaleMode property
of the object determines the unit of measure used. If the destination height is larger or smaller than the
source height (height2), the picture is stretched or compressed to fit. If omitted, the source height is used.
" x2, y2Single-precision values indicating the coordinates (x-axis and y-axis) of a clipping region within
the picture. The ScaleMode property of the object determines the unit of measure used. If omitted, 0 is
assumed.
" width2Single-precision value indicating the source width of a clipping region within the picture. The
ScaleMode property of the object determines the unit of measure used. If omitted, the entire source width

is used.
" height2Single-precision value indicating the source height of a clipping region within the picture. The
ScaleMode property of the object determines the unit of measure used. If omitted, the entire source height
is used.
" opcode Long value or code that is used only with bitmaps. It defines a bit-wise operation (such as
vbMergeCopy) that is performed on the picture as it is drawn on the object.




Visual Basic 6 Black Book:Picture Boxes And Image Controls
http://24.19.55.56:8080/temp/ch10\331-334.html (3 of 3) [3/14/2001 1:42:12 AM]
Simpo PDF Merge and Split Unregistered Version -


You can flip a bitmap horizontally or vertically by using negative values for the destination height
(height1) and/or the destination width (width1). For example, heres how we flip the image in Picture1
horizontally and display it in Picture2 (keep in mind that to draw from the Form_Load event, you
have to set the forms AutoRedraw property to True):

Private Sub Form_Load()
Picture2.PaintPicture Picture1.Picture, Picture1.ScaleWidth, 0, _
-1 * Picture1.ScaleWidth, Picture1.ScaleHeight
Picture2.Height = Picture1.Height
End Sub
The results of the preceding code appear in Figure 10.14. Now were flipping images in picture boxes.
Figure 10.14 Flipping an image in a picture box.
Printing A Picture
Can you print the image in a picture box out on the printer? You sure can, using the PaintPicture
method. To print on the printer, you just use the Visual Basic Printer object this way with

PaintPicture:

Printer.PaintPicture picture, x1, y1, [width1, height1, [x2, y2, _
[width2, height2, [opcode]]]]
Heres what the arguments passed to PaintPicture mean:
" pictureThe source of the graphic to be drawn onto the object (for example, Picture1.Picture).
" x1, y1Single-precision values indicating the destination coordinates (x-axis and y-axis) on the
object for the picture to be drawn. The ScaleMode property of the object determines the unit of
measure used.
" width1Single-precision value indicating the destination width of the picture. The ScaleMode
property of the object determines the unit of measure used. If the destination width is larger or smaller
than the source width (width2), the picture is stretched or compressed to fit. If omitted, the source
width is used.
" height1Single-precision value indicating the destination height of the picture. The ScaleMode
property of the object determines the unit of measure used. If the destination height is larger or smaller
than the source height (height2), the picture is stretched or compressed to fit. If omitted, the source
height is used.
Visual Basic 6 Black Book:Picture Boxes And Image Controls
http://24.19.55.56:8080/temp/ch10\334-337.html (1 of 4) [3/14/2001 1:42:23 AM]
Simpo PDF Merge and Split Unregistered Version -
" x2, y2Single-precision values indicating the coordinates (x-axis and y-axis) of a clipping region
within the picture (drawing operations outside the clipping region are ignored). The ScaleMode
property of the object determines the unit of measure used. If omitted, 0 is assumed.
" width2Single-precision value indicating the source width of a clipping region within the picture.
The ScaleMode property of the object determines the unit of measure used. If omitted, the entire
source width is used.
" height2Single-precision value indicating the source height of a clipping region within the picture.
The ScaleMode property of the object determines the unit of measure used. If omitted, the entire
source height is used.
" opcode Long value or code that is used only with bitmaps. It defines a bit-wise operation (such as

vbMergeCopy) that is performed on the picture as it is drawn on the object.
For example, heres how to print the picture in Picture1 on the printer:

Private Sub Command1_Click()
Printer.PaintPicture Picture1.Picture, 0, 0
End Sub
Thats all there is to itthe PaintPicture method is extraordinarily powerful. Note that before printing a
picture, you may want to display a Print dialog box (see the next chapter).
Using Picture Box Handles
You can gain even more control over whats going on in a picture box by using the various Windows
handles available for that control together with direct Windows API calls. Here are the picture box
handle properties:
" hDCHandle to the picture boxs device context
" hWndHandle to the picture boxs window
" ImageHandle to the picture boxs bitmap
" HandleDifferent handle types depending on the pictures Type property (for example,
Picture1.Picture.Type) as follows:
" Type = 1An HBITMAP handle
" Type = 2An HMETAFILE handle
" Type = 3An HICON or an HCURSOR handle
" Type = 4An HENHMETAFILE handle
For example, here we use the hDC property of a picture box to create a compatible bitmap and device
context matching the picture box, using the Windows API functions CreateCompatibleDC() and
Visual Basic 6 Black Book:Picture Boxes And Image Controls
http://24.19.55.56:8080/temp/ch10\334-337.html (2 of 4) [3/14/2001 1:42:23 AM]
Simpo PDF Merge and Split Unregistered Version -
CreateCompatibleBitmap() (these and all Windows API functions must also be declared in the
program, as well see in Chapter 23):

Private Sub Form_Load()

Picture1.Picture = LoadPicture("image.bmp")

Dim dcMemory As Long
Dim hMemoryBitmap As Long
dcMemory = CreateCompatibleDC(Picture1.hdc)
hMemoryBitmap = CreateCompatibleBitmap(Picture1.hdc, 60, 30)
End Sub
Setting Measurement Scales In A Picture Box
Picture boxes have a number of scale properties, and perhaps the most popular one is ScaleMode,
which sets the units of measurement in a picture box. Here are the possible values for ScaleMode (note
that when you set the scale mode of a picture box, all measurements are in those new units, including
coordinates passed to your program, like mouse-down locations):
" vbUser0; indicates that one or more of the ScaleHeight, ScaleWidth, ScaleLeft, and ScaleTop
properties are set to custom values
" vbTwips1(the default); Twip (1440 twips per logical inch; 567 twips per logical centimeter)
" vbPoints2; point (72 points per logical inch)
" vbPixels3; pixel (smallest unit of monitor or printer resolution)
" vbCharacters4; character (horizontal equals 120 twips per unit; vertical equals 240 twips per unit)
" vbInches5; inch
" vbMillimeters6; millimeter
" vbCentimeters7; centimeter
" vbHimetric8; hiMetric
" vbContainerPosition9; units used by the controls container to determine the controls position
" vbContainerSize10; units used by the controls container to determine the controls size
For example, in our image map example, we set the scale mode to pixels:

Private Sub Form_Load()
Picture1.ScaleMode = vbPixels
End Sub
Visual Basic 6 Black Book:Picture Boxes And Image Controls

http://24.19.55.56:8080/temp/ch10\334-337.html (3 of 4) [3/14/2001 1:42:23 AM]
Simpo PDF Merge and Split Unregistered Version -




Visual Basic 6 Black Book:Picture Boxes And Image Controls
http://24.19.55.56:8080/temp/ch10\334-337.html (4 of 4) [3/14/2001 1:42:23 AM]
Simpo PDF Merge and Split Unregistered Version -


Then we could use pixel dimensions in the MouseDown event:

Private Sub Picture1_MouseDown(Button As Integer, Shift As Integer, X As _
Single, Y As Single)
If X > 16 And X < 83 And Y > 11 And Y < 36 Then
MsgBox "You clicked the word ""Picture"""
End If

If X > 83 And X < 125 And Y > 11 And Y < 36 Then
MsgBox "You clicked the word ""Box"""
End If
End Sub
If you set the scale mode to vbUser, you can define your own units by setting the dimensions of the picture
box using the ScaleLeft, ScaleTop, ScaleWidth, and ScaleHeight properties. This can be very useful if you
re plotting points and want to use a picture box as a graph.
TIP: The ScaleWidth and ScaleHeight properties of a picture box hold the images actual dimensions (in
units determined by the ScaleMode property), not the Width and Height properties, which hold the controls
width and height (including the border).
Saving Pictures To Disk

We already know you can load pictures into a picture box with the LoadPicture function. Can you save them
to disk?
Yes, you can, using SavePicture. Heres how that statement works:

SavePicture picture, stringexpression
Heres what the parameters for SavePicture mean:
" picturePicture or image control from which the graphics file is to be created
" stringexpressionFile name of the graphics file to save
SavePicture only saves images in BMP, WMF, and ICO formats (depending on the file type the image came
from originally); if the image came from a GIF or JPEG file, its saved in BMP format. Graphics in an Image
property are always saved as bitmap (.bmp) files no matter what their original format.
Heres an example where we save the image from Picture1 to a file, C:\image.bmp, when the user clicks a
button:

Visual Basic 6 Black Book:Picture Boxes And Image Controls
http://24.19.55.56:8080/temp/ch10\337-340.html (1 of 3) [3/14/2001 1:42:34 AM]
Simpo PDF Merge and Split Unregistered Version -
Private Sub Command1_Click()
SavePicture Picture1.Picture, "c:\image.bmp"
End Sub
Adding An Image Control To A Form
Youve got 200 picture boxes in your program, and suddenly the Testing Department is on the line: your
program is causing users computers to run out of memory. No problem here, you say. They say, thats
because not everyone has 128MB of RAM like you doits time to decrease your programs memory
consumption.
One way of using fewer system resources is to use fewer picture boxes. As weve seen in this chapter, picture
boxes are powerful controlsand with that power comes lots of overhead. If youre just going to be displaying
images, use image controls instead. The image control uses fewer system resources and repaints faster than a
picture box (however, it supports only a subset of the picture box properties, events, and methods).
To install an image control, just use the Image Control tool in the toolbox. After adding the image control to

your form, just set its Picture property to the image file you want to display. By default, image controls shape
themselves to the image you display; if you want to stretch the image to fit the image control and not the other
way around, set the image controls Stretch property to True (the default is False).
As an example, weve placed an (unstretched) image in the image control in Figure 10.15.
Figure 10.15 Using an image control.
Stretching An Image In An Image Control
You can stretch (or flip) an image in a picture box using the PaintPicture method, but you cant use
PaintPicture with image controls. Is there still some way of producing interesting graphics effects in an
image control?
You can use the image controls Stretch property. By default, image controls shape themselves to fit the
images inside them (after all, their primary purpose is to display images), but if you set the Stretch property to
True (the default is False), the image control will stretch the image to fit the control.
As an example, were stretching an image in the image control in Figure 10.16.
Figure 10.16 Stretching an image in an image control.
You can also stretch an image in an image control by resizing the control (using its Width and Height
properties) at runtime as long as the controls Stretch property is True.



Visual Basic 6 Black Book:Picture Boxes And Image Controls
http://24.19.55.56:8080/temp/ch10\337-340.html (2 of 3) [3/14/2001 1:42:34 AM]
Simpo PDF Merge and Split Unregistered Version -

Visual Basic 6 Black Book:Picture Boxes And Image Controls
http://24.19.55.56:8080/temp/ch10\337-340.html (3 of 3) [3/14/2001 1:42:34 AM]
Simpo PDF Merge and Split Unregistered Version -


Chapter 11
Windows Common Dialogs

If you need an immediate solution to:
Creating And Displaying A Windows Common Dialog
Setting A Common Dialogs Title
Did The User Click OK Or Cancel?
Using A Color Dialog Box
Setting Color Dialog Flags
Using The Open And Save As Dialogs
Setting Open And Save As Flags
Getting The File Name In Open, Save As Dialogs
Setting Maximum File Name Size In Open And Save As Dialog Boxes
Setting Default File Extensions
Set Or Get The Initial Directory
Setting File Types (Filters) In Open, Save As Dialogs
Using A Font Dialog Box
Setting Font Dialog Flags
Setting Max And Min Font Sizes
Using The Print Dialog Box
Setting Print Dialog Flags
Setting The Minimum And Maximum Pages To Print
Setting Page Orientation
Showing Windows Help From A Visual Basic Program
In Depth
In this chapter, were going to examine the Windows Common Dialogs, which
provide a powerful and professional set of dialog boxes for interacting with the user.
Visual Basic 6 Black Book:Windows Common Dialogs
http://24.19.55.56:8080/temp/ch11\341-346.html (1 of 4) [3/14/2001 1:42:59 AM]
Simpo PDF Merge and Split Unregistered Version -
Microsoft created the Common Dialogs to promote a common user interface across all
Windows programs, and in fact the Common Dialogs do work welland they make
programming easier for the programmer. Having a common user interface across all

Windows programs is valuable for the user, because it simplifies tasks. For the
programmer, the Common Dialogs means that we have a powerful set of dialog boxes
ready for us to use, without having to create them ourselves. From both ends of the
spectrum, then, the Windows Common Dialogs may be considered a success.
The Common Dialog control can display five different dialog boxesOpen A File,
Save A File, Set A Color, Set A Font, and Print A Document.
The Common Dialog Control
The Common Dialogs are all part of one control: the Common Dialog control. You
add that control to a program with the Visual Basic Project|Components menu item.
Click the Controls tab in the Components box that opens, and select the entry labeled
Microsoft Common Dialog Control, then click on OK to close the Components box.
You add a Common Dialog control to a form in the usual wayjust double-click the
Common Dialog tool in the toolbox, or select it and paint the control on the form. The
Common Dialog tool appears as the eleventh tool down on the right in the Visual
Basic toolbox in Figure 11.1. The Common Dialog control will appear as a
nonresizable icon on your form and is not visible at runtime.
Figure 11.1 The Common Dialog tool.
You use the controls Action property to display a dialog box or, equivalently, these
methods:
" ShowOpenShow Open dialog box
" ShowSaveShow Save As dialog box
" ShowColorShow Color dialog box
" ShowFontShow Font dialog box
" ShowPrinterShow Print or Print Options dialog box
Besides these dialog boxes, you can also display Windows Help:
" ShowHelpInvokes the Windows Help engine
The Common Dialog control automatically provides context-sensitive Help on the
interface of the dialog boxes. You invoke context-sensitive Help by clicking the Help
button labeled Whats This in the title bar, then clicking the item for which you want
more information. In addition, you can right-click the item for which you want more

information, then select the Whats This command in the displayed context menu.
Visual Basic 6 Black Book:Windows Common Dialogs
http://24.19.55.56:8080/temp/ch11\341-346.html (2 of 4) [3/14/2001 1:42:59 AM]
Simpo PDF Merge and Split Unregistered Version -
TIP: We might also note, by the way, that there is no way currently to specify where
a dialog box is displayed; that might change in some future release.
As an example, the Font dialog box appears in Figure 11.2.
Figure 11.2 The Font dialog box.
Thats really all the overview we need. Were ready to start the Immediate Solutions
now.
Immediate Solutions
Creating And Displaying A Windows Common Dialog
The Testing Department is calling again. Your program, SuperDuperTextPro, is great,
but why is the File Save As dialog box the size of a postage stamp? And why is it
colored purple? Shouldnt it match the uniform kind of dialog box that other Windows
programs use?
To make your dialog boxes look just like the dialog boxes other programs use (and
add professionalism to your program), you can use the Windows Common Dialogs,
which are wrapped up in the Windows Common Dialog control. The Common Dialog
control can display five different dialog boxesOpen A File, Save A File, Set A Color,
Set A Font, and Print A Document, and you can also display Windows Help.
Adding a Windows Common Dialog control to your program is easy: just follow these
steps:
1. Select the Project|Components menu item.
2. Select the Controls tab in the Components box that opens.
3. Select the entry labeled Microsoft Common Dialog Control, then click on OK to
close the Components box.
4. Add a Common Dialog control to a form in the usual wayjust double-click the
Common Dialog tool in the toolbox, or select it and paint the control on the form.
(The Common Dialog tool appears as the eleventh tool down on the right in the Visual

Basic toolbox in Figure 11.1.)
5. Add the code you want to open the dialog box and make use of values the user
sets.
To display various dialog boxes, you use these Common Dialog methods (for
example, CommonDialog1.ShowColor):
" ShowOpenShow Open dialog box
Visual Basic 6 Black Book:Windows Common Dialogs
http://24.19.55.56:8080/temp/ch11\341-346.html (3 of 4) [3/14/2001 1:42:59 AM]
Simpo PDF Merge and Split Unregistered Version -
" ShowSaveShow Save As dialog box
" ShowColorShow Color dialog box
" ShowFontShow Font dialog box
" ShowPrinterShow Print or Print Options dialog box
" ShowHelpInvokes the Windows Help engine
You can also set the Common Dialogs Action property to do the same thing (and in
fact, thats the way you used to display Common Dialogs until recent Visual Basic
releases). Microsoft says that using the preceding methods adds functionality, but in
fact, the two ways of displaying dialog boxes are equivalent at this writing (although
using methods like ShowHelp instead of Action = 6 makes code a little clearer). Here
are the values you can place in the Action property:
" 0No action
" 1Displays the Open dialog box
" 2Displays the Save As dialog box
" 3Displays the Color dialog box
" 4Displays the Font dialog box
" 5Displays the Print dialog box
" 6Runs winhelp32.exe





Visual Basic 6 Black Book:Windows Common Dialogs
http://24.19.55.56:8080/temp/ch11\341-346.html (4 of 4) [3/14/2001 1:42:59 AM]
Simpo PDF Merge and Split Unregistered Version -


Now that youve added a Common Dialog control to your program, refer to the
individual topics in this chapter for the dialog box you want to work with to see how
to retrieve values from the user.
TIP: Before displaying the Font and Help dialog boxes, you need to set the Common
Dialogs controls Flags property or nothing will appear. See Setting Color Dialog
Flags, Setting Open and Save As Flags, Setting Font Dialog Flags, and Setting
Print Dialog Flags later in this chapter.
Setting A Common Dialogs Title
The Aesthetic Design Department is calling again: cant you change the text in the
title bar of those dialog boxes? How about changing the title of the Open dialog box
from Open to Select A File To Open?
Although some programmers may question the wisdom of changing a Common
Dialogs title, you can do it using the DialogTitle property. As an example, here were
changing the title of an Open dialog box to Select a file to open (see Figure 11.3):
Figure 11.3 Our dialog box with revised title.

Private Sub Command1_Click()
CommonDialog1.DialogTitle = "Select a file to open"
CommonDialog1.ShowOpen
End Sub
WARNING! Note that this property, DialogTitle, does not work for the Color, Font,
and Print dialog boxes.
Did The User Click OK Or Cancel?
Youve displayed your dialog box, and the user has dismissed it. But did the user click

the OK or the Cancel button? Should you take action or not?
You can check which button the user has selected by examining the various properties
of the dialog box controlfor example, when the user clicks Cancel in a File Open
dialog box, the FileName property returns an empty string, .
However, Visual Basic provides a more systematic way of checking which button was
Visual Basic 6 Black Book:Windows Common Dialogs
http://24.19.55.56:8080/temp/ch11\346-350.html (1 of 4) [3/14/2001 1:43:08 AM]
Simpo PDF Merge and Split Unregistered Version -
clicked. You can set the Common Dialog CancelError property to True to create a
special, nonharmful, and trappable error, error number 32755 (Visual Basic constant
cdlCancel), when the user clicks the Cancel button.
To trap this error if youve set the CancelError property to True, use On Error
GoTo, and place the label control at the end of the procedure:

Private Sub Command1_Click()
On Error GoTo Cancel

Cancel:
End Sub
Then you can show the dialog box and take action, assuming the user clicked on OK.
If, on the other hand, the user clicked Cancel, control will go to the end of the
procedure and exit harmlessly:

Private Sub Command1_Click()
On Error GoTo Cancel
CommonDialog1.ShowColor
Text1.BackColor = CommonDialog1.Color
Cancel:
End Sub
TIP: If you have enabled other trappable errors in your procedure (the On Error

GoTo statement in the preceding code does not affect code outside the procedure its
defined in), check to make sure that the error youre expecting when the user clicks
Cancel does in fact have the number cdlCancel. You can do this by checking the Err
objects Number property. Note also that Common Dialog controls can return errors
besides cdlCancelsuch as cdlHelp when the Help system failed to work properly, or
cdlFonts if no fonts existand you might check for those separately.
Using A Color Dialog Box
The Aesthetic Design Department is calling again. Wouldnt it be nice if you let the
user select the color of the controls in your program? Yes, you say, but&. Great, they
say, and hang up.
To let the user select colors, you use the Color dialog box, and you display that dialog
box with the Common Dialog method ShowColor. To retrieve the color the user
selected, you use the dialog boxs Color property. There are special flags you can set
for the Color dialog boxsee the next topic for more information.
Visual Basic 6 Black Book:Windows Common Dialogs
http://24.19.55.56:8080/temp/ch11\346-350.html (2 of 4) [3/14/2001 1:43:08 AM]
Simpo PDF Merge and Split Unregistered Version -
Lets see an example. When the user clicks a button, well display a Color dialog box
and let the user select the background color of a text box. Add a Common Dialog
control to a form and set its CancelError property to True so that clicking Cancel
will cause a cdlCancel error. Next, we trap that error this way:

Private Sub Command1_Click()
On Error GoTo Cancel

Cancel:
End Sub
Now we use the Common Dialog controls ShowColor method to show the color
dialog:


Private Sub Command1_Click()
On Error GoTo Cancel
CommonDialog1.ShowColor

Cancel:
End Sub
When control returns from the dialog box, we use the Color property to set the text
boxs background color to the color the user has selected:

Private Sub Command1_Click()
On Error GoTo Cancel
CommonDialog1.ShowColor
Text1.BackColor = CommonDialog1.Color
Cancel:
End Sub
Thats itwhen you run the program and click the button, the Color dialog box appears,
as in Figure 11.4.
Figure 11.4 The Color dialog box.
When the user selects a color and clicks on OK, the program sets the text boxs
background color to the newly selected color, as shown in Figure 11.5.
Visual Basic 6 Black Book:Windows Common Dialogs
http://24.19.55.56:8080/temp/ch11\346-350.html (3 of 4) [3/14/2001 1:43:08 AM]
Simpo PDF Merge and Split Unregistered Version -
Figure 11.5 Setting a controls color with the Color dialog box.
Now were using the Color dialog box. The listing for the preceding program is
located in the colordialog folder on this books accompanying CD-ROM.
Setting Color Dialog Flags
There are a number of options you can set before displaying a Color dialog box, and
you set them in the Flags property of the Common Dialog control. Here are the
possible values:

" cdlCCRGBInit1; sets the initial color value for the dialog box
" cdCClFullOpen2; entire dialog box is displayed, including the Define Custom
Colors section
" cdlCCPreventFullOpen4; disables the Define Custom Colors command button and
prevents the user from defining custom colors
" cdlCCHelpButton8; causes the dialog box to display a Help button
You can set more than one flag for a dialog box using the Or operator. For example:

CommonDialog1.Flags = &H10& Or &H200&
(Note that although this shows what were doing numerically, its usually better to use
constants to make the code more readable.) Adding the desired constant values
produces the same result.




Visual Basic 6 Black Book:Windows Common Dialogs
http://24.19.55.56:8080/temp/ch11\346-350.html (4 of 4) [3/14/2001 1:43:08 AM]
Simpo PDF Merge and Split Unregistered Version -


Using The Open And Save As Dialogs
Probably the most common use of the Common Dialog control is to display File Open
and File Save As dialog boxes, and you display those dialog boxes with the Common
Dialog controls ShowOpen and ShowSave methods. These methods need no
arguments passed to themto set various options, you set the Common Dialog controls
Flags property (see the next topic), such as overwriting existing files and so on.
You can also set the Filter property so the dialog box displays only certain types of
files, such as text files. See Setting File Types (Filters) In Open, Save As Dialogs a
little later in this chapter.

To find out what file the user wants to work with, you check the Common Dialogs
FileName property after the user clicks on OK in the dialog box. That property holds
the fully qualified (that is, with path) name of the file to open. If you just want the file
s name, use the FileTitle property.
Lets see an example. In this case, well let the user select a file to open, and then
display the files name and path in a message box.
Start by adding a Common Dialog control to a form, then set the controls
CancelError property to True so we can check if the user clicked Cancel. To check
that, we use On Error GoTo:

Private Sub Command1_Click()
On Error GoTo Cancel

Cancel:
End Sub
Then we display the Open dialog box:

Private Sub Command1_Click()
On Error GoTo Cancel
CommonDialog1.ShowOpen

Cancel:
End Sub
Finally, assuming the user clicked on OK, we can display the name of the file they
selected in a message box using the FileName property:

Visual Basic 6 Black Book:Windows Common Dialogs
http://24.19.55.56:8080/temp/ch11\350-353.html (1 of 4) [3/14/2001 1:43:18 AM]
Simpo PDF Merge and Split Unregistered Version -
Private Sub Command1_Click()

On Error GoTo Cancel
CommonDialog1.ShowOpen
MsgBox "File to open: " & CommonDialog1.FileName
Cancel:
End Sub
When you run this code and click the button, the Open dialog box appears, as in
Figure 11.6.
Figure 11.6 The Open dialog box.
If you make a file selection and click on OK, the Open dialog box closes and the
program displays the name of the file you selected, along with its path, in a message
box. Our program is a success; the code for this program is located in the opendialog
folder on this books accompanying CD-ROM.
Setting Open And Save As Flags
You can set a wide variety of options when you display File Open and File Save As
dialog boxes by setting the Common Dialog controls Flags property. Here are the
possible settings:
" cdlOFNAllowMultiselect&H200; specifies that the File Name list box allows
multiple selections.
" cdlOFNCreatePrompt&H2000; the user can select more than one file at runtime
by pressing the Shift key and using the up arrow and down arrow keys to select the
desired files. When this is done, the FileName property returns a string containing the
names of all selected files. The names in the string are delimited by spaces.
" cdlOFNCreatePrompt&H2000; specifies that the dialog box prompts the user to
create a file that doesnt currently exist. This flag automatically sets the
cdlOFNPathMustExist and cdlOFNFileMustExist flags.
" cdlOFNExplorer&H80000; displays the Explorer-like Open A File dialog box
template. Works with Windows 95 and Windows NT 4.
" cdlOFNExtensionDifferent&H400; indicates that the extension of the returned
file name is different from the extension specified by the DefaultExt property. This
flag isnt set if the DefaultExt property is Null, if the extensions match, or if the file

has no extension. This flag value can be checked upon closing the dialog box. This
can be useful if you want to track the kind of file the user wants to open.
" cdlOFNFileMustExist&H1000; specifies that the user can enter only names of
existing files in the File Name text box. If this flag is set and the user enters an invalid
Visual Basic 6 Black Book:Windows Common Dialogs
http://24.19.55.56:8080/temp/ch11\350-353.html (2 of 4) [3/14/2001 1:43:18 AM]
Simpo PDF Merge and Split Unregistered Version -
file name, a warning is displayed. This flag automatically sets the
cdlOFNPathMustExist flag.
" cdlOFNHelpButton&H10; causes the dialog box to display the Help button.
" cdlOFNHideReadOnly&H4; hides the Read Only checkbox.
" cdlOFNLongNames&H200000; enables the use of long file names.
" cdlOFNNoChangeDir&H8; forces the dialog box to set the current directory to
what it was when the dialog box was opened.
" cdlOFNNoDereferenceLinks&H100000; disables the use of shell links (also
known as shortcuts). By default, choosing a shell link causes it to be interpreted by the
shell.
" cdlOFNNoLongNames&H40000; disables long file names.
" cdlOFNNoReadOnlyReturn&H8000; specifies that the returned file wont have
the Read Only attribute set and wont be in a write-protected directory.
" cdlOFNNoValidate&H100; specifies that the Common Dialog allows invalid
characters in the returned file name.
" cdlOFNOverwritePrompt&H2; causes the Save As dialog box to generate a
message box if the selected file already exists. The user must confirm whether to
overwrite the file.
" cdlOFNPathMustExist&H800; specifies that the user can enter only valid paths.
If this flag is set and the user enters an invalid path, a warning message is displayed.
" cdlOFNReadOnly&H1; causes the Read Only checkbox to be initially checked
when the dialog box is created. This flag also indicates the state of the Read Only
checkbox when the dialog box is closed.

" cdlOFNShareAware&H4000; specifies that sharing violation errors will be
ignored.
You can set more than one flag for a dialog box using the Or operator. For example:

CommonDialog1.Flags = &H10& Or &H200&
(Although this shows what were doing numerically, its usually better to use
constants to make your code more readable.) Adding the desired constant values
produces the same result.



Visual Basic 6 Black Book:Windows Common Dialogs
http://24.19.55.56:8080/temp/ch11\350-353.html (3 of 4) [3/14/2001 1:43:18 AM]
Simpo PDF Merge and Split Unregistered Version -

Visual Basic 6 Black Book:Windows Common Dialogs
http://24.19.55.56:8080/temp/ch11\350-353.html (4 of 4) [3/14/2001 1:43:18 AM]
Simpo PDF Merge and Split Unregistered Version -


Getting The File Name In Open, Save As Dialogs
Now that youve used the Common Dialog controls ShowOpen or ShowSave to display an Open
or Save As dialog box, how do you get the file name the user has specified? You do that using one
of two properties after the user clicks on the OK button:
" FileNameHolds the file name the user selected, with the files full path.
" FileTitleHolds just the files name, without the path.
Heres an example where weve set a Common Dialog controls CancelError property to True so
Visual Basic will create a trappable cdlCancel error if the user clicks the Cancel button, show a
File Open dialog box, and display the name and path of the file the user selected in a message box:


Private Sub Command1_Click()
On Error GoTo Cancel
CommonDialog1.ShowOpen
MsgBox "File to open: " & CommonDialog1.FileName
Cancel:
End Sub
You can set the Filter property so the dialog box displays only certain types of files, such as text
files. The Flags property can be used to change various elements on the dialog box, as well as to
prompt the user when certain actions may occur, such as overwriting a file. See Setting File Types
(Filters) In Open, Save As Dialogs for more on filters. For more on flags, see Setting Color
Dialog Flags, Setting Open and Save As Flags, Setting Font Dialog Flags, and Setting Print
Dialog Flags later in this chapter.
Setting Maximum File Name Size In Open And Save As Dialog Boxes
You can use the Common Dialog controls MaxFileSize property to setnot the maximum file size
you can open, but the maximum file name size. You set this property to a number of bytes as
follows, where were restricting the file name and path to fit into 100 bytes:

CommonDialog1.MaxFileSize = 100
This is useful if youre passing file names to other programs that cant use names longer than a
certain length.
TIP: When using the cdlOFNAllowMultiselect flag, you may want to increase the value in the
MaxFileSize property to allow enough memory for the selected file names.
Visual Basic 6 Black Book:Windows Common Dialogs
http://24.19.55.56:8080/temp/ch11\354-358.html (1 of 4) [3/14/2001 1:43:23 AM]
Simpo PDF Merge and Split Unregistered Version -
Setting Default File Extensions
Like many Windows programs, you can make your programs set the default extension for the
types of files you want to save (for example, .txt) if the user doesnt specify one. You specify a
default extension with the Common Dialog controls DefaultExt property.
An example will make this clearer. Here, we set the default extension of our files to save to txt by

setting the DefaultExt property:

Private Sub Command1_Click()
On Error GoTo Cancel
CommonDialog1.DefaultExt = "txt"
CommonDialog1.ShowSave
MsgBox "File to save: " & CommonDialog1.FileName
Cancel:
End Sub
Lets say the user just types a file name without an extension, such as phonebook, in the Save As
dialog box; the dialog box will then report the actual name of the file to save as phonebook.txt. If,
on the other hand, the user specifies a file extension, that extension is preserved.
Set Or Get The Initial Directory
The Testing Department is calling again: users of your program, SuperDuperTextPro, are
complaining. When they want to save many files to their favorite directory,
C:\poetry\roses\are\red\violets\are\blue, they have to open folder after folder each time to get back
to that directory. Cant you let them set a default directory to save files to?
You can, using the Common Dialog controls InitDir property. For example, heres how we set
the initial directory to C:\windows when we open files using the Open dialog box:

Private Sub Command1_Click()
On Error GoTo Cancel
CommonDialog1.InitDir = "c:\windows"
CommonDialog1.ShowOpen
MsgBox "File to open: " & CommonDialog1.FileName
Cancel:
End Sub
Running this code results in the Open dialog box you see in Figure 11.7.
Visual Basic 6 Black Book:Windows Common Dialogs
http://24.19.55.56:8080/temp/ch11\354-358.html (2 of 4) [3/14/2001 1:43:23 AM]

Simpo PDF Merge and Split Unregistered Version -
Figure 11.7 Setting an initial directory.
Setting the initial directory like this can make multiple opens or saves much easier, which is very
considerate to the user (and I know of some Microsoft software that could benefit by doing this).
Setting File Types (Filters) In Open, Save As Dialogs
The Testing Department is calling again. Your program, SuperDuperGraphics4U, only works
with graphics files, but somehow users are trying to open text (.txt) filesand crashing the program.
Is there some way you can clue them in as to allowed file types when they open files?
Yesyou can set the Common Dialog controls Filter property to indicate the allowed file types
and extensions in a drop-down list box in the Open and Save As dialog boxes. (To see an example
of such a drop-down list box, use Visual Basics Save Project As menu item in the File menu; this
list box gives two file extension types: *.vbp and all files, *.*.)
To set up the Filter string, you separate prompts to the userfor example, Text files (*.txt)with
upright characters (|, also called the pipe symbol) from the file specifications to Visual Basic (
*.txt). (Dont add extra spaces around the uprights, because if you do, theyll be displayed along
with the rest of the file extension information.)
This is obviously one of those things made easier with an example (in fact, I always forget how to
set up file filter strings unless I can work from an example), so lets see one now. Here, well let
the user select from three options: text files (*.txt), image files (*.jpg, *.gif), and all files (*.*). We
set the Filter string this way in that case; look closely at the following string and youll be able to
see how to set up this string for yourself. (Here weve also set the Common Dialog controls
CancelError property to True to create a trappable error if the user clicks the Cancel button):

Private Sub Command1_Click()
On Error GoTo Cancel
CommonDialog1.Filter = "Text files (*.txt)|*.txt|Image files _
(*.jpg, *.gif)|*.jpg;*.gif|All files (*.*)|*.*"
CommonDialog1.ShowOpen
MsgBox "File to open:  & CommonDialog1.FileName
Cancel:

End Sub
Note in particular that when you have two file extensions for one file typeas we do for image files
(*.jpg, *.gif)you surround the file extensions with a semicolon (;) and enclose them in
parentheses.
The result of this code appears in Figure 11.8. Here, were letting the user select from our three
types of files: text files (*.txt), image files (*.jpg, *.gif), and all files (*.*).
Visual Basic 6 Black Book:Windows Common Dialogs
http://24.19.55.56:8080/temp/ch11\354-358.html (3 of 4) [3/14/2001 1:43:23 AM]
Simpo PDF Merge and Split Unregistered Version -

×