A dialog box is a small window used to display or accept information. Its name comes from the fact that it is, in essence, a dialog (or conversation) with the user. A dialog box is usually shown modally, which means the user must close it (or "answer the dialog") before continuing with any other part of the program. This chapter looks at two dialog boxes built in to the Visual Basic language: the message box and the input box. Next, you use the CommonDialog custom control, which allows you to place four types of standard dialog boxes in your program. Finally, you see some guidelines for creating your own form-based dialog box.
A big part of any programming project is providing information to users about the program's progress and status. While the forms and controls of your program provide the main interface to the user, they are not necessarily the best vehicles for providing bits of information that require immediate attention, such as warnings or error messages. For providing this type of information, the message box is the way to go.
The message box is a simple form that displays a message and at least one command button. The button is used to acknowledge the message and close the form. Because message boxes are built in to the Visual Basic language, you do not have to worry about creating or showing a form. To see a simple message box, type the following line of code into Visual Basic's Immediate window (choose View, Immediate Window to open the window) and press Enter:
MsgBox "Hello World!"
Optionally, the message box can display an icon or use multiple buttons to let the user make a decision. This is done with the use of optional parameters. For example, the following code line produces the message box shown in Figure 6.1:
MsgBox "Delete record?", vbYesNo + vbExclamation, "Confirm Delete"
NOTE: You can try it yourself. Just type the code in the Immediate window and press Enter.
FIG. 6.1
A message box commu-nicates with the user.
Message boxes can be used in either of two ways, depending on your needs. You can use the message box to simply display information, or you can use it to get a decision from the user. In either case, you will use some form of the MsgBox function.
NOTE: Although this chapter refers to them interchangeably, there is a conceptual difference between using MsgBox as a function and a statement. By definition, a function returns a value, whereas a statement does not. Also, the syntax for parameters is slightly different--a function's parameters must be enclosed in parentheses. For example, if you wanted to see the return value from the MsgBox function, you could type the following line in the Immediate window:
Print MsgBox ("Delete record?", vbYesNo + vbExclamation, "Confirm Delete")
While the message box is very useful, it does have a few limitations:
The simplest way to create a message box in your program is to use the MsgBox function as a statement, without returning a value. When using the MsgBox function this way, you simply specify the message text that you want to appear in the message box and then call the function. For the simplest message, only the OK button is shown in the message box. This allows the user to acknowledge the message:
MsgBox "Please insert a disk in Drive A:"
When you specify the message text, you can use a literal constant (a string of text enclosed in quotes, as shown above) or a string variable, as in this example:
Dim stMyText as String stMyText = "Hello," & vbCrLf & "World" MsgBox stMyText
Note the use of the intrinsic (predefined) constant vbCrLf (which you learned about in Chapter 4, "Working with Forms and Controls"), representing a carriage return/line feed combination, to make "Hello" and "World" appear on separate lines.
See "Working with Text," Chapter 4
The default message box uses the project name for its caption and has only an OK button. You can dress up your messages a little bit with two optional parameters--the buttons argument and the title argument. The buttons argument is an integer number that can specify the icon to display in the message box, the command button set to display, and which of the command buttons is the default. The title argument is a text string that specifies custom text to be shown in the title bar of the message box. The full syntax of the MsgBox function is as follows:
MsgBox(prompt[, buttons] [, title] [, helpfile, context])
If you choose to display an icon in the message box, you have a choice of four icons. These icons and their purposes are summarized in Table 6.1.
Icon |
Icon Name | Purpose |
|
Critical Message | Indicates that a severe error has occurred. Often a program is shut down after this message. |
|
Warning Message | Indicates that a program error has occurred that requires user correction or that may lead to undesirable results. |
|
Query Message | Indicates that the program requires additional information from the user before processing can continue. |
|
Information Message | Informs the user of the status of the program. Often used to notify the user of the completion of a task. |
To tell Visual Basic that you want to use an icon in the message box, you set a value for the buttons argument of the MsgBox function. The buttons argument can be set to one of four values, as defined in the following table. You can use either the numerical value or the constant from the table:
Options Message Type | Argument Value | Constant |
Critical | 16 | vbCritical |
Query | 32 | vbQuestion |
Warning | 48 | vbExclamation |
Information | 64 | vbInformation |
TIP: Good programming practice dictates that you use the appropriate constant to represent the integer value. This makes your programs more readable and will not require any conversion should Microsoft change the integer values.
NOTE: The constants listed in the preceding table not only affect the icon that is displayed, but also the sound produced by Windows when a message appears. You can set sounds for different message types in the Windows Control Panel.
To illustrate how icons and titles can be used in your message boxes, the following code produces the message box shown in Figure 6.2:
MsgBox "This message box contains an icon.", vbInformation, "Icon Demo"
FIG. 6.2
Use titles and icons to give the user visual cues to the nature of the message.
If you are wondering how you are going to remember the syntax of the MsgBox function and the constants to be used for the options, don't worry. The new statement completion capabilities of Visual Basic's Code Editor help tremendously with this. When you type the space after the MsgBox function name in a Code window (or the Immediate window, for that matter), a pop-up appears that shows you the syntax of the command (see Figure 6.3).
FIG. 6.3
Syntax help assists you in setting up the message box.
Then, after you enter the message to be displayed and enter a comma, Visual Basic pops up a list of constants that can be used to add an icon to the message box or to specify the button set to be used. You can select one of the constants from the list or type it in yourself. This is one of the really great new features in the editor. Figure 6.4 shows the constants list in action.
The MsgBox function, as described previously, works fine for informing users of a problem or prompting them to take an action. However, to get a decision from the user, you need to use the MsgBox function's return value. There are two key differences to using the MsgBox function this way--you (usually) assign the function's return value to a variable, and you must enclose the arguments of the function in parentheses. This value reports which command button was clicked by the user. The following line of code shows how the value returned by the function can be assigned to a variable for further processing:
inResult = MsgBox("The printer is not responding", vbRetryCancel, "Printer Error!")
Additional statements after the preceding code could check the value of the variable inResult with, for example, an If statement, and take appropriate action.
FIG. 6.4
You no longer have to remember the options' constants with the pop-ups available
in the editor.
Six sets of command buttons can be used in the MsgBox function:
To specify the command buttons that will appear in the message box, you need to specify a value for the buttons argument of the MsgBox function. The values for each of the command button sets are listed in Table 6.2.
Button Set | Value | Constant |
OK | 0 | vbOKOnly |
OK, Cancel | 1 | vbOKCancel |
Abort, Retry, Ignore | 2 | VBAbortRetryIgnore |
Yes, No, Cancel | 3 | vbYesNoCancel |
Yes, No | 4 | vbYesNo |
Retry, Cancel | 5 | vbRetryCancel |
Because the buttons argument controls both the icon and the command-button set for a message box, you might wonder how you can specify both at the same time. You do this by adding the values of the constants together. The MsgBox function is designed so that any combination of the icon constant and the command-button constant creates a unique value. This value is then broken down by the function to specify the individual pieces. The following code combines an icon constant and command button constant to create a warning message that allows the user to choose an action. The results of the code are illustrated in Figure 6.5.
inOptVal = vbExclamation + vbAbortRetryIgnore inRetVal = MsgBox("File does not exist.", inOptVal, "My Application")
TIP: When you are using the pop-up constants list, you can select a second constant for the options parameter by entering a plus sign (+) after selecting the first constant.
NOTE: If you want your message box to display a Help button, add the constant vbMsgBoxHelpButton, which has a value of 16384, to whichever button set constant you choose.
FIG. 6.5
The buttons argument controls both the icon and the command buttons displayed
by the MsgBox function.
If you are using more than one command button in the message box, you can also specify which button is the default. The default button is the one that has focus when the message box is displayed. This button is the one that the user is most likely to choose so that he can just press the Enter key. For example, if you display a message box to have the user confirm the deletion of the record, you probably should set up the default button so that the record would not be deleted. This way, the user must make a conscious choice to delete the record.
To specify which button is the default, you need to add another constant to the buttons argument of the MsgBox function. The four possible default button values are identified in the following table:
Default Button | Value | Constant |
First | 0 | vbDefaultButton1 |
Second | 256 | vbDefaultButton2 |
Third | 512 | vbDefaultButton3 |
Fourth | 768 | vbDefaultButton4 |
A user might choose from seven buttons, with the selection depending on the button set used in the message box. Each button returns a different value to identify the button to your program (see Table 6.3).
Button | Value | Constant |
OK | 1 | vbOK |
Cancel | 2 | vbCancel |
Abort | 3 | vbAbort |
Retry | 4 | vbRetry |
Ignore | 5 | vbIgnore |
Yes | 6 | vbYes |
No | 7 | vbNo |
As always, it is preferable to use the constant in your code rather than the actual integer value. After you know which button the user selected, you can use that information in your program. The following code is used to confirm the deletion of a file:
Dim stFileName As String Dim stMsgTitle As String Dim stMsgText As String Dim inReturn As Integer Dim inOptions As Integer stFileName = "C:\MYDIR\MYFILE.TXT" stMsgText = "Do you really want to delete `" & stFileName & "`?" inOptions = vbQuestion + vbYesNo + vbDefaultButton2 stMsgTitle = "Delete Confirmation" inReturn = MsgBox(stMsgText, inOptions, stMsgTitle) If inReturn = vbYes Then Kill stFileName MsgBox stFileName & " has been deleted.",vbInformation,"File deleted" End If
For completeness, one final setting can be applied to the buttons argument of the MsgBox function. You can choose to have the message box be modal for your application or for the entire system. Remember from earlier chapters that when a modal window is shown, it must be closed before continuing with the program. If you specify that the message box is modal to the system, the user must respond to the message box before he can do any further work on the computer at all. The system modal option should be used with extreme care. The default behavior is application modal, which means the user could continue to work in other applications.
To use the default of application modal, you do not have to add anything to the buttons argument, or you can add the vbApplicationModal constant, which has a value of 0. To make the message box system modal, you need to add the constant vbSystemModal, which has a value of 4096, to the buttons argument.
Many times in a program, you need to get a single piece of information from the user. You might need the user to enter a person's name, the name of a file, or a number for various purposes. Although the message box lets your users make choices, it does not allow them to enter any information in response to the message. Therefore, you have to use some other means to get the information. Visual Basic provides a built-in dialog box for exactly this purpose: the input box.
The input box displays a message to tell the user what to enter, a text box where the user can enter the requested information, and two command buttons--OK and Cancel--that can be used to either accept or abort the input data. A sample input box is shown in Figure 6.6.
FIG. 6.6
An input box lets the user enter a single piece of data in response to a message.
Programmatically, the input box works very much like the message box with a return value. You can specify a variable to receive the information returned from the input box and then supply the input box's message (prompt) and, optionally, a title and default value. An example of the InputBox function is the following:
Dim stMsg as String, stUserName As String stMsg = "Please type your name below:" stUserName = InputBox(stMsg, "Enter user name", "Anonymous")
In this statement, the information returned by the InputBox function will be stored in the variable stUserName. The first argument, the prompt parameter, represents the message that is displayed to the user to indicate what should be entered in the box. Like the message in the message box, the prompt can be up to 1,024 characters. Word-wrapping is automatically performed on the text in the prompt so that it fits inside the box. Also, as with the message box, you can insert a carriage return/line-feed combination (vbCrLf) to force the prompt to show multiple lines or to separate lines for emphasis.
After the prompt comes the title argument, which specifies the text in the input box's title bar. The other argument in the preceding example is the default argument. If included, it appears as an initial value in the input box. This value can be accepted by the user, modified, or it can be erased and a completely new value entered.
The minimum requirement for the InputBox function is a prompt parameter, as in the statement
stReturnVal = InputBox("How's the weather?")
In addition to the input box's optional parameters to specify a window title and default value, other optional parameters allow you to set its initial screen position, as well as the help file to be used if the user needs assistance. Refer to the complete syntax of the InputBox function in Visual Basic's help system.
NOTE: Unlike the MsgBox function, there is no option in the InputBox function to specify any command buttons other than the defaults of OK and Cancel.
When the input box is used, the user can enter up to 254 characters of text in the input box's entry area, which resembles a text box. If he types more text than will fit in the displayed entry area, the text he's already typed will scroll to the left. Once he's done, he can choose the OK or Cancel button. If he chooses the OK button, the input box returns whatever is in the text box, whether it is new text or the default text. If the user clicked the Cancel button, the input box returns an empty string, regardless of what is in the text box.
To be able to use the information entered by the user, you must determine if the data meets your needs. First, you probably want to make sure that the user actually entered some information and chose the OK button. You can do this by using the Len function to determine the length of the returned string. If the length is zero, the user pressed the Cancel button or left the input field blank. If the length of the string is greater than zero, you know that the user entered something. To see how the Len function works, enter each of these lines in the Immediate window and note the different results:
Print Len("Hello") Print Len("")
You may also need to check the returned value to make sure it is of the proper type. If you are expecting a number that will subsequently be compared to another number in an If statement, your program should present an error message if the user enters letters. To make sure that you have a numerical value with which to work, you can use the Val function, which returns the numerical value of a string. If the string contains or starts with numbers, the function returns the number. If the string does not start with a number, the function returns zero. To understand the Val function, enter these lines in the Immediate window to see what each returns:
Print Val("Hello") Print Val("50 ways to leave your lover") Print Val("100 and 1 make 101")
The following code illustrates additional processing of the returned value of the input box with Val and Len:
Dim stInputVal As String stInputVal = InputBox("Enter your age") If Len(stInputVal) = 0 Then MsgBox "No age was selected" Else If Val(stInputVal) = 0 Then MsgBox "You entered an invalid age." Else MsgBox "Congratulations for surviving this long!" End If End If
In earlier sections, you learned what a dialog box is and how to use two simple dialog boxes. In this section, you learn about the Microsoft CommonDialog control, which allows you to use standard Windows dialog boxes to specify file names, select fonts and colors, and control the printer. And while the ease of setup is a great benefit, an even bigger bonus is that these dialog boxes are already familiar to the user. This is because they are the same dialog boxes used by Windows itself.
When using a single CommonDialog control, you have access to the following standard Windows dialog boxes:
Although the CommonDialog control is included with Visual Basic, it's not one of the controls included in the Toolbox by default. To access the CommonDialog control, you might first have to add it to your project (and to the Toolbox) by selecting it from the Components dialog box. This dialog box is accessible by choosing Project, Components. From there, select Microsoft Common Dialog Control 5.0 in the Controls list and click OK.
After the CommonDialog control is added to the Toolbox, you can add the control to a form by clicking the control and drawing it on the form just like any other control. The CommonDialog control appears on your form as an icon, as the control itself is not visible when your application is running.
The following sections discuss each type of dialog box that can be created with the CommonDialog control. For each of these dialog boxes, you need to set some of the control's properties. You can do this through the Properties window, or you can use the CommonDialog control's Property Pages dialog box. The Property Pages dialog box provides you easy access to the specific properties that are necessary for each of the common dialog box types (see Figure 6.7). You can access the Property Pages dialog box by clicking the ellipsis (...) button in the Custom property of the CommonDialog control, or by right-clicking the control and selecting Properties.
FIG. 6.7
The Property Pages dialog box makes it easy to set up the CommonDialog control.
One of the key uses of the CommonDialog control is to obtain file names from the user. The CommonDialog control's File dialog box can be used in either of two modes: Open and Save As. Open mode lets the user specify the name and location of a file to be retrieved and used by your program. Save As mode lets the user specify the name and location of a file to be saved.
The dialog boxes for the Open and Save As functions are very similar. Figure 6.8 shows the Open dialog box.
FIG. 6.8
The Open and Save dialog boxes share many components.
These are the dialog box's major components:
Opening and Saving Files To open an existing file, use the ShowOpen method of the CommonDialog control. (This method displays the dialog box in Figure 6.8.) You use this method by specifying the name of the CommonDialog control and the method name, as shown in the following lines of code:
cdlGetFile.ShowOpen Msgbox "You Selected " & cdlGetFile.FileName
After the preceding code is executed, the name of the file selected is available to your code in the control's FileName property.
Using the CommonDialog control for saving and opening are essentially the same operation. The name of the method used to invoke the Save As dialog box is ShowSave. There are a few subtle differences between the dialog boxes shown for the Open and Save functions, such as the title of the dialog box and the captions on the command buttons.
NOTE: The Open and Save As dialog boxes don't actually open or save files; they simply get information from the user as to the names and locations of the files to open or save. It's up to your program to take whatever steps are necessary to complete the operation.
Specifying File Types with the Filter Property When using the CommonDialog control, you might find it necessary to specify that only certain file types are listed. If your program reads Microsoft Excel (.XLS) files, for example, you would not want the user to attempt to open a batch (.BAT) file. You can restrict (or "filter") the files shown in the dialog box by using the Filter property. You set the Filter property at design mode from either the Properties window or the Property Pages dialog box, or at runtime with an assignment statement in code. The Filter property is a string value that includes a file type description followed by the file extension. It requires a special format, as shown here:
cdlGetFile.Filter = "Word Documents|*.DOC"
The vertical line in the preceding code line is known as the pipe symbol. This symbol must be present in the filter. Preceding the pipe symbol is a short description of the file type--in this case, Word Documents. Following the pipe symbol is the actual filter for the files. You typically express the filter as an asterisk followed by a period and the extension of the files that you want to display. Some examples are *.txt, *.doc, and *.*.
CAUTION: Do not include spaces before or after the pipe symbol, or you might not get the file list that you want.
If you specify the Filter property with an assignment statement, you must enclose the filter in double quotes, as with any string. The quotes are omitted if you specify the filter from the Properties dialog box.
You can specify multiple description|filter pairs within the Filter property. Each pair must be separated from the other pairs by the pipe symbol, as shown in the following example:
cdgGetFile.Filter = "All Files|*.*|Text Files|*.txt"
Customizing the File Dialog Boxes with the Flags Property Another important property is the Flags property. The Flags property is set by using a constant or combination of constants, similar to the MsgBox function's Options parameter. A complete list of constants is listed in Visual Basic's Help system. For example, if the Open as Read Only check box doesn't make any sense in your program, you can set a flag to hide it:
cdlFile.Flags = cdlOFNHideReadOnly cdlFile.InitDir = "C:\Windows" cdlfile.ShowOpen
Note also the use of the InitDir property, which starts the dialog box in a specific folder.
NOTE: Flags, filters, and properties that affect the CommonDialog box must be set before displaying it!
Setting up the CommonDialog control to show the Font dialog box is just as easy as setting it up for file functions. In fact, you can use the same CommonDialog control on a form to handle file, font, color, and printer functions, just by resetting the properties and invoking the appropriate method.
The first step in using the CommonDialog control to handle font selection is to set a value for the Flags property. Among other things, this property tells the CommonDialog control whether you want to show screen fonts, printer fonts, or both. This setting is required; the constants are listed in the following table:
Font Set | Constant | Value |
Screen fonts | cdlCFScreenFonts | 1 |
Printer fonts | cdlCFPrinterFonts | 2 |
Both sets | cdlCFBoth | 3 |
CAUTION: If you do not set a value for the Flags property, you get an error message stating that no fonts are installed.
You can set the value of the Flags property from the design environment--by using the Properties window or the Property Pages dialog box--or from your program by using an assignment statement. After the Flags property has been set, you can invoke the Font dialog box from your code, using the CommonDialog's ShowFont method. After the dialog box is closed, information about the font that the user selected is contained in the CommonDialog's properties:
cdlFont.flags = cdlCFBoth + cdlCFEffects cdlFont.ShowFont txtName.Font.Name = cdlFont.FontName txtName.Font.Size = cdlFont.FontSize txtName.Font.Bold = cdlFont.FontBold
Note two things in the preceding code. First, an extra flag, cdlCFEffects, allows the user to select additional font "effects" such as bold, color, and underline. Second, note the slight difference in syntax between the TextBox's Font properties and the CommonDialog's Font properties. The Font property of a text box is an object itself (a Font object), while the CommonDialog box stores each attribute about a font (Name, Size, Bold, and so on) in a separate property. The text box has the older separate properties for compatibility, but I would avoid them. If you had to set the font for two text boxes, you could set one directly from the CommonDialog control's properties and the other one simply by assigning the first text box's Font property:
txtAddress.Font = txtName.Font
Figure 6.9 shows the Font dialog box that is presented to the user. This particular dialog box contains both screen and printer fonts.
FIG. 6.9
The Font dialog box can be programmed to display screen fonts, printer fonts,
or both.
Table 6.4 shows the control's properties and the font attributes that each manipulates.
Property | Attribute |
FontName | The name of the base font |
FontSize | The height of the font in points |
FontBold | Whether boldface was selected |
FontItalic | Whether italic was selected |
FontUnderline | Whether the font is underlined |
FontStrikethru | Whether the font has a line through it |
The font information can be used to set the font of any object in your program, or even to set the font for the Printer object. Be sure to peruse the Help system for a complete list of Flags property constants.
The CommonDialog control's Color dialog box lets the user select colors that can be used for the foreground or background colors of your forms or controls (see Figure 6.10). The user has the option of choosing one of the standard colors or creating and selecting a custom color.
FIG. 6.10
The Color dialog box lets the user select a color graphically and then returns
it to your program as a hex value.
Setting up the CommonDialog control for colors is basically the same as for fonts. You set the Flags property to the constant cdlCCRGBInit and then invoke the control's ShowColor method.
When the user selects a color from the dialog box, a hexadecimal number representing that color is stored in the Color property of the control. The following code shows how to change a form's background color using the Color dialog box:
cdlGetColor.Flags = cdlCCRGBInit cdlGetColor.ShowColorfrmMyForm.BackColor = cdlGetColor.Color
As with the other dialog boxes, you can alter the behavior of the Color dialog box with the Flags property. For example, if you want only default colors available, use the cdlCCPreventFullOpen flag so the user cannot open the Define Custom Colors window.
Another type of dialog box provided by the CommonDialog control is the Print dialog box. A Print dialog box is usually displayed just before your application's print process begins. It lets the user select which printer to use and specify options for the print process (see Figure 6.11). These options include specifying which pages to print and the number of copies, as well as an option of printing to a file.
To invoke the Print dialog box, just call the CommonDialog control's ShowPrinter method. There are no required flags to set prior to the call.
After the Print dialog box is displayed, the user can select the printer from the Name list at the top of the dialog box. This list contains all the printers installed in the user's operating system. Just below the Name list is the Status line, which tells you the current status of the selected printer.
FIG. 6.11
The Print dialog box provides a consistent way for your users to set printer
options.
If users want to change any printer-specific parameters (such as paper size and margins), they can click the Properties button on the Print dialog box. This brings up the Properties dialog box for the selected printer, as shown in Figure 6.12. This dialog box lets you control all the settings of the printer, just as with the Windows Control Panel.
FIG. 6.12
The Properties dialog box for the printer lets you control paper size, margins,
and other printer attributes.
The Print dialog box returns the information provided by the user in the dialog box's properties. The FromPage and ToPage properties tell you the starting and ending pages of the printout as selected by the user. The Copies property tells you how many copies the user wants printed.
This is provided only as information. The Print dialog box does not automatically create the desired printout. As with other CommonDialogs, your program must complete the task, as in this example:
cdlPrint.Flags = cdlPDDisablePrintToFile cdlPrint.Copies = 3 cdlPrint.PrinterDefault = True cdlPrint.ShowPrinter MsgBox "The default printer is:" & Printer.DeviceName
In this sample code, properties and flags are used to disable the Print to File option and set the default number of copies to 3. In addition, the PrinterDefault property means that the dialog box will use the control's properties to modify the default system printer.
This usage of the CommonDialog control invokes the Windows Help engine by running WINHLP32.EXE. To use this dialog box, you must set the CommonDialog control's HelpFile property to the name and location of a properly formatted Windows help (.hlp) file and set the HelpCommand property to tell the Help engine what type of help to offer. After setting these properties, use the CommonDialog control's ShowHelp method to initiate the Help system. The user can then navigate the Help system by using your program's Help file.
Although the CommonDialog control provides you with a number of dialog boxes to use in your programs, sometimes some things just can't be accomplished with these built-in tools. For example, if you want to set your own captions for the command buttons in a dialog box, you can't do this with the message box, nor can the message box handle more than three buttons. Also, consider the built-in input box. This dialog box cannot display an icon, nor can it handle more than one input item. So what are you supposed to do? Build your own, of course.
In this section, you see how to build a simple, but flexible, dialog box to display a message and a set of custom command buttons. Your dialog box will allow you to choose to have from one to three buttons displayed and will be able to display any of four icons. From this example, you will be able to see how you can build more complex dialog boxes.
The first thing you have to do in creating a dialog box is to create the form itself. To do this, follow these steps:
With these property settings, your dialog box will start up in the center of the screen and will have a border that, like standard Windows dialog boxes, doesn't allow the user to resize it. In addition, it won't have the Control Menu icon at the left-hand side of the title bar.
NOTE: The Project window now contains two files, one for each of the two forms. When you save the project, you need to supply file names for both form (.FRM) files, as well as a file name for the overall project (.VBP) file.
Now that you have created a dialog-style form, the next step is to add a Label control to display your message to the user.
Next, you will want to add Image controls that will display the icon in the dialog box. You'll be using five Image controls--the one that the user actually sees, and four other (invisible) Image controls that will hold the four icons that could possibly be displayed in the visible control. The ImageList control technique discussed in Chapter 5, "Adding Menus and Toolbars to Your Program," could also have been used here.
See "Getting the Images for Your Toolbar," Chapter 5
Continue building the dialog box form as follows:
This technique allows your program to display only the requested number of buttons when the dialog box is called. Make sure that all the command buttons are the same size. When you have finished, your form should look something like the one in Figure 6.13.
FIG. 6.13
Your custom dialog box will have several command buttons and images to allow
choices.
While placing the controls on the form is a critical part of creating a custom dialog box, the main work of the dialog box is done with code.
First, you need to have a way for the user to set the dialog box's options before showing it. This is accomplished with public variables. Chapter 8, "Programming Basics" discusses public variables more fully; for now, think of a public variable as something that acts much like a property that applies to the form in which it is declared. It can be accessed from any part of your application by using the form name, a dot, and the variable name (for example, frmMain.stFileName).
See "Variable Declarations," Chapter 8
You declare public variables in the form's General Declarations section:
Option Explicit Public inNumCmd as Integer Public inImageID as Integer Public stCmdCaption1 as String Public stCmdCaption2 as String Public stCmdCaption3 as String Public inBtnPressed As Integer
The main part of your code will be located in the form's Activate event procedure. The Activate event occurs when the form becomes the "active" form. Your code controls which image and command buttons are visible to the user and properly positions them on the form. The code, shown in Listing 6.1, assumes that all the command buttons are the same size. By setting the Top, Left, and Visible properties of the buttons, the visible command buttons are shown near the bottom of the label control that displays the message. The Left property of each button is set so that the button group is centered in the form. And the height of the form itself is adjusted so that there is not a lot of empty space showing.
Private Sub Form_Activate() Dim inCtlTop As Integer Dim inCmdWidth As Integer `First, select an image based `on the ImageID public variable: Select Case inImageID Case 1 imgShow.Picture = Image1.Picture Case 2 imgShow.Picture = Image2.Picture Case 3 imgShow.Picture = Image3.Picture Case 4 imgShow.Picture = Image4.Picture End Select `The tops of the controls will be `240 twips below the message label: inCtlTop = lblMessage.Top + lblMessage.Height + 240 cmdMessage1.Top = inCtlTop cmdMessage2.Top = inCtlTop cmdMessage3.Top = inCtlTop `The form will be sized 500 twips below the buttons Me.Height = cmdMessage1.Top + cmdMessage1.Height + 500 `Set the CommandButton captions cmdMessage1.Caption = stCmdCaption1 cmdMessage2.Caption = stCmdCaption2 cmdMessage3.Caption = stCmdCaption3 `Set the CommandButton visible properties Select Case inNumCmd Case 2 cmdMessage2.Visible = True Case 3 cmdMessage2.Visible = True cmdMessage3.Visible = True End Select `Finally, center the buttons on the form Select Case inNumCmd Case 1 inCmdWidth = cmdMessage1.Width cmdMessage1.Left = (frmDialog.ScaleWidth - inCmdWidth) / 2 Case 2 inCmdWidth = 2 * cmdMessage1.Width + 105 cmdMessage1.Left = (frmDialog.ScaleWidth - inCmdWidth) / 2 cmdMessage2.Left = cmdMessage1.Left + cmdMessage1.Width + 105 Case 3 inCmdWidth = 3 * cmdMessage1.Width + 2 * 105 cmdMessage1.Left = (frmDialog.ScaleWidth - inCmdWidth) / 2 cmdMessage2.Left = cmdMessage1.Left + cmdMessage1.Width + 105 cmdMessage3.Left = cmdMessage2.Left + cmdMessage2.Width + 105 End Select End Sub
Another thing that you want your dialog box to be able to do is to tell the calling program which button was pressed. You handle this by using the Public variable inBtnPressed that was declared in frmDialog's General Declarations section. The dialog box will set a different value of the variable for each command button (see Listing 6.2). You will also want to unload the form when any command button has been pressed. This ensures that the dialog box is reset when it is reloaded (causing the Load event to occur again).
Private Sub cmdMessage1_Click() inBtnPressed = 1 Unload Me End Sub Private Sub cmdMessage2_Click() inBtnPressed = 2 Unload Me End Sub Private Sub cmdMessage3_Click() inBtnPressed = 3 Unload Me End Sub
Now that you have entered all the code, you are ready to use it! This involves three basic steps:
To test the dialog box, put a command button on the other form in your project and enter the sample code in Listing 6.3.
Private Sub Command1_Click() Dim stMsg as string stMsg = "This is a dialog with a custom set of buttons. This is something that stMsg = stMsg & "cannot be achieved with a normal message box." With frmDialog .lblMessage.Caption = stMsg .NumCmd = 2 .ImageID = 4 .CmdCaption1 = "&Discard File" .CmdCaption2 = "&Save File" .Show vbModal Msgbox "You pressed " & .BtnPressed End With End Sub
Notice in the listing that you can use a With...End With statement block to avoid typing frmDialog over and over. A sample of the custom dialog box is shown in Figure 6.14.
FIG. 6.14
Though there is a lot of room for improvement, your custom dialog box behaves
just like a standard Windows message box.
By using the procedures illustrated in this section, you can create any kind of dialog box that you want. In addition, Microsoft has included with Visual Basic 5 several form templates representing custom dialog boxes that are common to many programs. You can quickly add one of these form templates to your project by selecting the appropriate type when you add a new form; you can then customize it to suit your needs. The available templates include:
You can add these forms based on these dialog box templates to your program by choosing Project, Add Form, or by clicking the Add Form button. This presents you with the Add Form dialog box shown in Figure 6.15. You can choose the desired dialog box from the templates available, and then customize it to suit your needs.
FIG. 6.15
Several custom dialog boxes are available as form templates.
You have seen in this chapter how dialog boxes can be used to help the user select files, printers, and fonts in your programs. You have also seen how the message box and input box are used to inform the user and to get decisions or single pieces of information. You have even seen how to create your own dialog boxes when the built-in ones are insufficient for the task. To learn more about using some of the concepts presented here, take a look at the following chapters:
© Copyright, Macmillan Computer Publishing. All rights reserved.