Hour 17


During this hour you will learn

Adding Control Containers: Dialog Boxes

This lesson explains how to add dialog boxes to your programs. A dialog box is a container that holds a set of controls. Common dialog boxes are the dialog boxes you see when you open files, save files, and print documents. To streamline your programming efforts and to ensure application consistency, Visual Basic includes the common dialog box control, which produces a standard dialog box that performs these and other common dialog box operations.

Before the common dialog box control, you had to tediously design dialog boxes by placing controls on each dialog box that you wanted to create. Virtually every programmer created a slightly different dialog box, so applications lost the consistency so important in the Windows environment. The common dialog box control not only maintains this consistency but is easy to use.

Topic 1: Introducing Common Dialog Boxes

Although Visual Basic includes file-related controls such as the directory list box and file list box controls, you don't have to deal with these controls if you want to provide a file-related dialog box for your users. All you need to do is place the common dialog box control on your form and set the properties that specify the dialog box's purpose. The same is true for many other dialog boxes you've seen used in various applications.

FAST TRACK
Even if you've already used the common dialog box control in other Visual Basic versions, you need to read the section "Getting Ready" to learn how to add the Common Dialog Box tool to your Toolbox. After you add this tool, you can jump to Hour 18, "Using Additional Controls".

Overview

The common dialog box control is a multi-talented control. It lets you place several types of dialog boxes on your form:

Hour 29, "Building a Help Subsystem," explains more about the WinHelp common dialog box feature.

This topic sections in this lesson explain how to produce common dialog boxes in the applications you distribute so that your users can more quickly adapt to your programs and can conveniently provide input responses when needed.

Getting Ready

Tools for all controls that you place on a form reside in the Toolbox. Therefore, you can't add the common dialog box control to any forms until the Common Dialog Box tool appears in the Toolbox. This tool normally isn't in the Toolbox, so you have to add it by following these steps:

  1. Choose Components from the Project menu to display the Components dialog box shown in Figure 17.1.

FIG. 17.1

You can add tools to the Toolbox by using the Components dialog box.

  1. Scroll down to the control named Microsoft Common Dialog Control 5.0 if you don't already see this control in the dialog box, and then click it.
  2. Click OK. The tool now appears in your Toolbox (see Figure 17.2).

FIG. 17.2

The Common Dialog Box tool now appears in the Toolbox.

You might wonder why you have to add certain tools to the Toolbox. As you can see from the Components dialog box, Visual Basic comes with many controls. If the Toolbox held a tool representing every available control, the Toolbox would be flooded with tools and would consume far too much of your development environment's screen. Therefore, Microsoft puts the most common controls in the default Toolbox and allows you to add other controls when and if you need them.

Many software vendors offer additional Visual Basic controls. Be on the lookout for useful controls that perform tasks you may need, such as reporting, communicating, or displaying graphics. Although Visual Basic's tool set is powerful and fairly complete, other tools sometimes offer flexibility and usefulness that can come in handy in certain situations. Check your online service or the Internet for additional tools that you can purchase (or sometimes even download for free).

Dialog Box Response

Your running application will display the dialog boxes that the common dialog box control provides, and Visual Basic will receive information based on user input or selected values within the dialog box. Your application then acts on the dialog box information. Your application, in other words, won't open a file just because you've displayed an Open dialog box and users have selected a file. The common dialog box controls simply provide a standard mechanism that your program can use to find out what users really want.

When your application is ready to open a data file, for example, you display the Open dialog box (assume that users have triggered the file opening, perhaps by choosing the File menu's Open command). Users then select the file to open or cancel the operation. Your program then determines what to do based on what happened in the dialog box. You can tell whether users have canceled the operation (by clicking the dialog box's Cancel button) or selected a file (by using the dialog box's file-selection features). If users have selected a file, your application knows the exact file location and name, but your code must then open the file and read the data by using standard file-access procedures. Without follow-up code, an Open dialog box would just go away when users selected a file, and no file activity would take place.

Dialog Box Placement

When you first place a dialog box on your form, you don't see anything that looks like a dialog box. For example, you never see the Open dialog box in the form window. The common dialog box control appears only as a small icon in the form window. You can move the common dialog box control icon out of the way to see other, more important controls.

As long as you've placed a common dialog box control somewhere on the form, your application can display the appropriate dialog box when needed. The common dialog box control acts like a general-purpose control that can turn into a specific dialog box as often as needed.

You can place as many common dialog box controls on your form as you want. If you plan to display an Open dialog box, a Save dialog box, and a Print dialog box at various times, you can place three common dialog box controls on your form and set up each one in the Properties window to do a specific job. Alternatively, you can place just one common dialog box control on the form, and then set the appropriate options at runtime each time you're ready to produce one of the specific dialog boxes.

Example

Figure 17.3 shows a new form window that contains a single common dialog box control. As you can see, the control doesn't look at all like an actual dialog box.

FIG. 17.3

The common dialog box control takes up very little room.

When you place a common dialog box control on a form, Visual Basic won't let you resize the control. The control's size depends on what you turn the control into with properties. All you can-and should-do is move the control out of the way of your other controls. The common dialog box control just sits there and waits for your running program to trigger its execution.

The common dialog box control is invisible at runtime, so the control's location on the form doesn't matter.

Next Step

Your code will use one of these methods to trigger the display of one of the common dialog boxes:

For example, if you name a common dialog box control dbPrint, your code to display the Print dialog box (which might be found in the mnuFilePrint_Click () event procedure for theFile menu's Print command) would be the following:

dbPrint.ShowPrinter     ' Activate the Print dialog box

Now that you understand how to place and activate the common dialog box control, you need to understand that you must set up dialog boxes before you activate them. Therefore, the remaining two topic sections describe the normal process you go through to set up specific common dialog box controls. After you set up a control, you'll learn how to access user responses for the dialog box.

All the common dialog boxes are modal. Users must close the dialog box by clicking OK or Cancel before they can continue with any other part of the application.

Topic 2: Working with Color and Fonts

The Color and Font dialog boxes are fairly easy to generate and respond to. Your users will appreciate that you've used standard dialog boxes in your application. Also, the standard dialog boxes make it easier to write your application because you don't have a different set of rules for several different-but-similar dialog boxes that you might have created without the standard.

Overview

Using Color and Font dialog boxes in your applications requires these fundamental steps that subsequent sections explain in more detail:

  1. Place the common dialog box control on your form.
  2. Before any code displays the dialog box, set up the dialog box default values.
  3. Include code that shows the dialog box.
  4. When control returns to your application, inspect the user's values and respond accordingly.

The Color Dialog Box

Figure 17.4 shows the Color dialog box that the common dialog box control produces.

FIG. 17.4

The Color dialog box provides a color selection palette.

Colors provide an interesting challenge to many Windows programmers. Windows supports thousands of color shades, and a different number represents each possible color. Inside Windows programs, the number often appears as a hexadecimal (base 16) number called the RGB number (it's RGB because a particular Red/Green/Blue combination produces the specific shade). Fortunately, the Color dialog box means that you don't have to worry too much about RGB numbers. When users close the Color dialog box, the chosen number appears in the common dialog box control's Color property.

Users have the option of clicking the Color dialog box's Define Custom Colors button to display the color spectrum tool (see Figure 17.5). The color spectrum tool lets users select an exact color from a prism of colors, and then adds that color to the basic colors in the Color dialog box for subsequent selection.

FIG. 17.5

Users can select from a color spectrum.

Two properties that you should set before displaying the Color dialog box are DialogTitle and Flags. DialogTitle displays a title in the Color dialog box's title bar. Flags determines how the dialog box appears. Table 17.1 lists the flag values you can use for the Color dialog box. You can combine these values by adding them together if you want to specify several values in the same dialog box.

Table 17.1 Color Dialog Box Flags Values

Named Literal

Flags Value

Description

cdlCCRGBInit
1

Sets the initial color value

cdlCCFullOpen
2

Displays the entire dialog box, including the Define Custom Colors section

cdlCCPreventFullOpen
4

Prevents users from defining custom colors

cdlCCHelpButton
8

Displays a Help button in the dialog box

The Font Dialog Box

Figure 17.6 shows the Font dialog box that the common dialog box control produces.

FIG. 17.6

The Font dialog box provides a font selection.

The fonts vary depending on the computer on which your application is running. The Font dialog box ensures that the font is available to your application, because the fonts come from the current machine and not from the computer that produced the program. Before you print or display certain text, you may want to give each user a chance to format the text (perhaps with the Format menu's standard Font command), so display the Font dialog box and then assign the selected values to the user's text.

You must set the proper Font dialog box Flags value from Table 17.2. Otherwise, the Font dialog box won't appear.

Table 17.2 Font Dialog Box Flags Values

Named Literal

Flags Value

Description

cdlCFANSIOnly
&H400
Ensures that the dialog box allows only fonts from the Windows character set and not a symbol-based font

cdlCFApply
&H200
Enables the dialog box's Apply button

cdlCFBoth
&H3
Lists the available printer and screen fonts in the dialog box; the hDC property identifies the device context associated with the printer

cdlCFEffects
&H100
Lets the dialog box enable strikethrough, underline, and color effects

cdlCFFixedPitchOnly
&H4000
Ensures that the dialog box selects only fixed-pitch fonts

cdlCFForceFontExist
&H10000
Displays an error message box if users try to select a font or style that doesn't exist

cdlCFHelpButton
&H4
Displays the dialog box's Help button

cdlCFLimitSize
&H2000
Ensures that the dialog box selects only font sizes within the range specified by the Min and Max properties

cdlCFNoFaceSel

&H80000

No font name is selected as the default

cdlCFNoSimulations

&H1000

Disallows graphic device interface (GDI) font simulations

cdlCFNoSizeSel

&H200000

No font size is selected as the default

cdlCFNoStyleSel

&H100000

No font style is selected as the default

cdlCFNoVectorFonts

&H800

Disallows vector-font selections

cdlCFPrinterFonts

&H2

Lists only the fonts supported by the printer, specified by the hDC property

cdlCFScalableOnly

&H20000

Allows only the selection of scalable fonts

cdlCFScreenFonts

&H1

Lists only the screen fonts supported by the system

cdlCFTTOnly

&H40000

Allows only the selection of TrueType fonts

cdlCFWYSIWYG

&H8000

Specifies that the dialog box allows only the selection of fonts available on the printer and on-screen (if you set this flag, you should also set cdlCFBoth and cdlCFScalableOnly)

You must set at least one of the following values before the Font dialog box appears correctly: cdlCFScreenFonts, cdlCFPrinterFonts, or cdlCFBoth. Otherwise, Visual Basic issues an error message.

You may need to set more than one Flags value, such as cdlCFNoStyleSel and cdlCFScreenFonts. Use the logical And or Or operator to combine these Flags values, as in the following assignment:

cdbFontDB.Flags = cdlCFNoStyleSel And cdlCFScreenFonts

After you set the Flags property, apply the ShowFont method to the dialog box to display the Fonts dialog box. You can't set multiple Flags at design time, only at runtime.

Example

Suppose that you've added two common dialog box controls, cdbColor and cdbFont, to a form. To activate and respond to the Color dialog box, you might code a procedure section that looks something like this:

' Set the Color Flags property.

cdbColor.Flags = cdlCCFullOpen  ' Display complete Color DB

' Display the Color dialog box.

cdbColor.ShowColor

' Set a label's foreground color

' to the dialog box's selected color.

lblMessage.ForeColor = cdbColor.Color

You might set up and respond to the Font dialog box like this:

' Set the Font Flags property.

CdbFont.Flags = cdlCFBoth Or cdlCFEffects

CdbFont.ShowFont  ' Display the Font DB

' Set a label's properties to the

' user's selected font information

LblMessage.Font.Name = CdbFont.FontName

LblMessage.Font.Size = CdbFont.FontSize

LblMessage.Font.Bold = CdbFont.FontBold

LblMessage.Font.Italic = CdbFont.FontItalic

LblMessage.Font.Underline = CdbFont.FontUnderline

LblMessage.FontStrikethru = CdbFont.FontStrikethru

LblMessage.ForeColor = CdbFont.Color

Pay attention to the multipart assignments of the first five properties when this code returns from the dialog box display. There are several values, each of which indicates a different kind of font. Read such multipart names from right to left. Consider the following statement:

LblMessage.Font.Bold = CdbFont.FontBold

This tells Visual Basic to assign the dialog box's FontBold property (which is either True or False) to the Bold attribute of the Font property of the label named lblMessage.

One problem with the code presented here is that no provision is made for a Cancel click in the dialog box. To test to see whether users have clicked Cancel, you need to learn a new Visual Basic command-the On Error Goto statement. This statement jumps the program execution down to a code label if an error occurs during subsequent statements. Therefore, the statement

On Error Goto dbErrHandler

tells Visual Basic to jump to the code labeled dbErrHandler if an error occurs during any line that follows the On Error Goto statement (until the end of the procedure).

A code label is a label inside your Code window's code that you name using the same naming rules used for variables. A label, however, must end in a colon to distinguish it from a variable name. With the example just given, the procedure must have the following code label somewhere after the On Error Goto statement (generally, programmers put the error code label toward the bottom of the procedure):

dbErrHandler:

The statements after the error-handling code label are executed if an error occurs in the procedure and an Exit statement terminates the procedure early. Visual Basic triggers an error condition if users click the Cancel button and you've set the CancelError property to True. Although clicking Cancel isn't a real error, treating it like an error condition lets you write code like that in Listing 17.1 to handle it.

Listing 17.1 Cancel.bas: Controlling the User's Cancel Selection

Private Sub cmdMessage_Click()

  cdbFont.CancelError = True  ' Causes an error if

                              ' user clicks Cancel

  On Error Goto dbErrHandler  ' Jump if an error occurs

' Set the Font Flags property.

  CdbFont.Flags = cdlCFBoth Or cdlCFEffects

  CdbFont.ShowFont  ' Display the Font DB

  ' Set a label's properties to the

  ' user's selected font information

  LblMessage.Font.Name = CdbFont.FontName

  LblMessage.Font.Size = CdbFont.FontSize

  LblMessage.Font.Bold = CdbFont.FontBold

  LblMessage.Font.Italic = CdbFont.FontItalic

  LblMessage.Font.Underline = CdbFont.FontUnderline

  LblMessage.FontStrikethru = CdbFont.FontStrikethru

  LblMessage.ForeColor = CdbFont.Color

  Exit Sub

dbErrHandler:

  ' The user clicked cancel so ignore the proc

  Exit Sub

End Sub

Rather than end the procedure if users click Cancel, you might choose to set default values for the label rather than retain the current values and exit the procedure.

Next Step

Although you can set all the common dialog box control properties at runtime, Visual Basic provides an ingenious way to set some properties at design time.

The common dialog box control contains a property named Custom. When you click the ellipsis for this property setting in the Properties window, Visual Basic displays the Property Pages dialog box (Figure 17.7 shows the dialog box's Font page).

FIG. 17.7

You can set properties at design time from the Property Pages dialog box.

The Property Pages dialog box makes it easy for you to set some initial dialog box properties. Here you can review the most important properties for each style of common dialog box. For example, if you want the Font dialog box's default font to be 12-point Bold, type 12 in the FontSize text box and click to select the Bold check box.

Topic 3: The Remaining Dialog Boxes

Now that you've mastered the Color and Font dialog boxes-including the necessary handling if Cancel is clicked-the remaining dialog boxes are simple.

Overview

The Open and Save common dialog boxes are virtually identical, and you set them up in almost the same manner. The key difference is that the Open dialog box displays a list of files from which users select one (or more) to open, whereas the Save dialog box lets your users select a single file name (and location) to use for saving data. You need to worry only about setting certain default values.

The Print dialog box prepares users for printing to whatever printer (or fax) they select. Your program can read the Print dialog box responses to know how many copies users want and where they wants the printed output sent.

The Open Dialog Box

Figure 17.8 shows the Open dialog box that the common dialog box control produces.

FIG. 17.8

The Open dialog box lets users select a file to open.

The Open dialog box ensures that users select a valid computer (in a networked environment), drive, path name, and file name.

Although you don't have to set any Flags values before displaying the Open dialog box, Table 17.3 lists the optional Flags values you might want to set before triggering the dialog box's ShowOpen method.

Table 17.3 The Open and Save Dialog Boxes' Flags Values

Named Literal

Flags Value

Description

cdlOFNAllowMultiselect

&H200

Lets the File Name list box accept multiple file selections. The FileName property then returns a string that contains all the selected file names (names in the string are delimited by spaces).

cdlOFNCreatePrompt

&H2000

Prompts users to create a file that doesn't currently exist. This flag automatically sets the cdlOFNPathMustExist and cdlOFNFileMustExist flags.

cdlOFNExplorer

&H80000

Uses the Explorer-like Open a File dialog box template.

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 contains Null, if the extensions match, or if the file has no extension. You can inspect this flag's value after the dialog box is closed.

cdlOFNFileMustExist

&H1000

Lets users enter only names of existing files. If this flag is set and users enter an invalid file name, a warning is displayed. This flag automatically sets the cdlOFNPathMustExist flag.

cdlOFNHelpButton

&H10

Displays the dialog box's Help button.

cdlOFNHideReadOnly

&H4

Hides the Read Only check box.

cdlOFNLongNames

&H200000

Allows 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

Disallows dereferencing of shell links (also known as shortcuts). By default, choosing a shell link causes it to be dereferenced by the shell.

cdlOFNNoLongNames

&H40000

Disallows 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

Allows invalid characters in the returned file name.

cdlOFNOverwritePrompt

&H2

Causes the Save As dialog box to generate a warning message box if the selected file already exists (users then choose whether to overwrite the existing file).

cdlOFNPathMustExist

&H800

Lets users enter only valid paths. If this flag is set and the users enter an invalid path, a warning message is displayed.

cdlOFNReadOnly

&H1

Selects the Read Only check box when the dialog box is created. This flag also indicates the state of the Read Only check box after the dialog box is closed.

cdlOFNShareAware

&H4000

Indicates that possible sharing violation errors will be ignored.

When you display an Open dialog box, you may want to specify a filter for the file-name extensions that the box shows. This determines the file types that the users see in the Files of Type text box, but they can override these extensions. To specify the filter, type the desired extensions in the Filter property. The file types appear in the Files of Type text box, separated by semicolons. The filter, if you specify one, is a string and must conform to this format:

"FilterDescrip1 | extension1 | FilterDescrip2 | extension2 | FilterDescrip3 | extension3"

For example, the following statement assigns a filter that shows only Word and Excel documents when the Open dialog box appears:

cmdFiles.Filter = "Word Docs (*.doc)|*.doc|

[ccc]Excel Docs (*.xls)|*.xls"

Don't confuse the file extensions in the description with the actual extensions in the filter. In the example, Word Docs (*.doc) is text to be displayed to users, and the *.doc following the first pipe symbol is the dialog box's first actual filtering instruction.

You can supply multiple filters by including multiple strings for the Filter property. If you specify more than one filter, you must set the FilterIndex property to the filter you want to use for the current Open dialog box. The first filter has a FilterIndex of 1; this number is incremented if you supply additional filters.

The common dialog box control's FileName property holds the selected file name after users close the dialog box.

The Save Dialog Box

Figure 17.9 shows the Save dialog box that the common dialog box control produces when you apply the ShowSave method to the control's name.

FIG. 17.9

The Save dialog box lets users select a file name to use for saving data. (The Save dialog box becomes the Save As dialog box if you've yet to name the file you are saving.)

Review the differences between the Save and Open dialog boxes. They're both used to help users select a file name, but although users can save data to only one file name, they can-if your application and the Flags property allow-select multiple files to open from the Open dialog box. Also, the Save dialog box grays out all existing file names and displays only the directory paths to files.

The Save dialog box uses the same Flags values as the Open Flags values you saw in Table 17.4.

The Print Dialog Box

Figure 17.10 shows the Print dialog box that the common dialog box control produces when you apply the ShowPrinter method to the control name. Users can select the printer type, number of copies, range of pages, and several other printing options. Each printer setup for the users' system displays a different set of Print dialog box options. When users enter the desired values, your application can use that information (taken from the common dialog box control's properties) to direct the print output properly.

FIG. 17.10

The Print dialog box lets users select printer options.

Your Print dialog box will vary from Figure 17.10, depending on your printer type.

Example

Figure 17.11 shows the Open dialog box that results from the procedure in Listing 17.2.

Listing 17.2 Filter.bas: Creating Advanced Open Dialog Boxes

Private Sub mnuFileOpen_Click ()

' Assumes CancelError is True

  On Error Goto dbErrHandler

  ' Determine what appears in

  ' the Files of type text box

  cdbFile.Filter = "Text Files (*.txt) | *.txt"

  ' Specify default filter

  cdbFile.FilterIndex = 1

  ' Display the Open dialog box.

  cdbFile.ShowOpen

  ' *****

  ' You must place code here or call

  ' a procedure to open the file

  ' selected by the user

  ' *****

  Exit Sub  ' Don't fall through

dbErrHandler:

  ' User clicked the Cancel button

  Exit Sub  ' Don't open a file

End Sub

FIG. 17.11

You can limit a Open dialog box to show only text files.

Next Step

The code in Listing 17.3 displays a Print dialog box and checks to see whether Cancel is clicked.

Listing 17.3 Printdb.bas: Using the Common Dialog Box to Direct Printed Output

Private cmdPrintIt_Click()

  Dim intBegin As Integer, intEnd As Integer

  Dim intNumCopies As Integer, intI As Integer

  ' Assumes Cancel is set to True

  On Error Goto dbErrHandler

  ' Display the Print dialog box

  cbdPrint.ShowPrinter

  ' Get user-selected values from the dialog box

  intBegin = cbdPrint.FromPage

  intEnd = cbdPrint.ToPage

  intNumCopies = cbdPrint.Copies

  For intI = 1 To intNumCopies

    ' Put code here to send data to your printer

  Next intI

  Exit Sub

dbErrHandler:

  ' User pressed Cancel button

  Exit Sub

Summary

In this lesson, you mastered the common dialog box control. This control becomes any of the following specific dialog boxes: Color, Font, Open, Save, Print, and Help.

The common dialog box control is invisible on your form when the application runs. At design time, you can place the control anywhere that's out of the way of other controls you want to work with in the form window.

When users trigger a situation that requires a dialog box, you use code to set appropriate dialog box properties and display the dialog box (you have no control over where the dialog box appears). The resulting dialog box is a standard Windows dialog box that will be familiar to your users. When users make selections in the dialog box and close it, your code uses the information by accessing the common dialog box control properties.

In Hour 18, you'll add a few more controls to your repertoire so that you can customize your applications to their fullest.

Hour 17 Quiz

  1. What must you do to your Toolbox before you can work with the common dialog box control?
  2. Name the specific dialog boxes that the common dialog box control displays.
  3. What purpose does the common dialog box control serve?
  4. Why can't you adjust the size of the common dialog box control on your form?
  5. True or false: The Open dialog box doesn't really open anything.
  6. What role does the Filter property play in the file-related dialog boxes?
  7. What does the Flags property do?
  8. True or false: You must set a Flags value, or Visual Basic won't display the Fonts dialog box.
  9. True or false: You must set a Flags value, or Visual Basic won't display the Print dialog box.
  10. True or false: The Show method displays a common dialog box control.

Hour 17 Homework Exercises

  1. Write a filter that displays an Open dialog box showing files with these extensions and descriptions:

DescriptionExtension
Microsoft PowerPoint*.ppt
ASCII Text Files*.asc
Visual Basic Project Files*.vbp

  1. Create a text box that displays the words Your Text. Before displaying the text box, ask users for font information that will determine the way the text box displays its contents.
  2. Write a small application that contains one command button and one common dialog box control. When users click the command button, ask them for a color and then change the form background to that color.

© 1997, QUE Corporation, an imprint of Macmillan Publishing USA, a Simon and Schuster Company.