Using Visual Basic 6

Previous chapterNext chapterContents


- 14 -
Enhancing Your Programs with Forms and Dialog Boxes


Creating Message Boxes with the MsgBox() Function and the MsgBox Statement

Message boxes are simple forms that display messages and at least one CommandButton that's used to acknowledge the message (see Figure 14.1). Optionally, a message box can display an icon or use multiple buttons to let users make a decision. You can use a message box to display information or to obtain a decision from the user.

FIGURE 14.1 A message box is task modal, meaning that the application can't continue until the message box is closed.

You can display a message box by using the MsgBox statement or the MsgBox() function. The difference between them is that the function displays the message box and returns a value, but the statement only displays the message box. Also, there's a slight syntactical difference--the use of parentheses and a return value are required for the MsgBox() function.

Using the MsgBox() function is valuable if you need your program's users to make a decision and you want to respond to that decision. For example, if you want to ask users if they want to proceed with a process, you would use the following statements:


Visual Basic constants

Visual Basic has many predefined constants that you can use when programming with message boxes. For instance, you use vbYesNo to display a message box with Yes and No buttons. Using these internal constants is discussed in detail later in the section, "Retrieving a Value from the MsgBox() Function."


Dim iResponse as Integer
iResponse = MsgBox("Do you want to proceed", vbYesNo, App.Name)
If iResponse = vbYes then
    `Place your proceed code here
End If

The syntax for a MsgBox statement is

MsgBox strMessage, [Options][, strTitle][, strHelpFile][, _
       HelpContextID]

The following MsgBox statement displays the message box shown in Figure 14.1:

Private Sub Command1_Click()
    MsgBox "I am a Message Box"
End Sub

The syntax for a MsgBox() function is

RetInt = MsgBox(strMessage[, Options][, strTitle][, _
                strHelpFile][, HelpContextID])

In both sets of syntax, the following options and keywords are used:


Using message boxes for error messages

If you decide to use a message box to report an error, remember the three fundamental rules for reporting an error: State the error, inform users of what they most likely did to cause the error, and suggest a way to correct the error.


The simple message box is acceptable for many types of messages, but you will probably want to dress up your messages a little more as you progress into more complex programming. You can specify two optional arguments for the MsgBox statement and the MsgBox() function: Options and strTitle. The Options argument is an integer that specifies the icon to display in the message box, the CommandButton(s) set to display, and which of the CommandButtons is the default. The strTitle argument is a text string that specifies a custom text to be shown in the title bar of the message box. Figure 14.2 shows a simple message box that has been enhanced to show an icon and additional buttons. The following code displays this message box:

Private Sub Command2_Click()
    MsgBox "I am a Fancy Message Box", _
           vbInformation + vbYesNoCancel, _
           "Message Box Title"
End Sub

FIGURE 14.2 You can add icons and additional buttons to a message box.

Adding Icons to Message Boxes

You have a choice of four icons to display in a message box. These icons and their purposes are summarized in Table 14.1.

TABLE 14.2  Icons and Icon Constants

Icon Constant Purpose
vbCritical A critical message indicates that a severe error has occurred. Often, a program is shut down after this message.
vbExclamation A warning message indicates that a program error has occurred that requires user correction or might lead to undesirable results.
vbQuestion A query indicates that the program requires additional information from users before processing can continue.
vbInformation An information message informs users of the status of the program. This is most often used to notify users of a task's completion.


Using multiple constants

When you use the pop-up constants list, you can select a second constant by entering a plus sign (+) after the first constant.


If you're wondering how you're going to remember the syntax of the MsgBox statement/function and the constants to be used for the options, don't worry. The statement completion capabilities of Visual Basic's Code Editor help tremendously. When you type the space after the MsgBox statement/function name in the code window, a pop-up shows you the syntax of the command (see Figure 14.3).

FIGURE 14.3 The statement completion feature of Visual Basic lets you select the constants appropriate to your needs.

As you type in the function name, 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 a constant from the list by pressing Ctrl+Enter or typing it yourself.

Retrieving a Value from the MsgBox() Function

The MsgBox statement works fine for informing users of problems or prompting them to take an action. If you need to obtain a decision from users, however, you must return a value by using the MsgBox() function.

You can use six sets of CommandButtons in the MsgBox() function:

To specify the CommandButtons that will appear in the message box, you need to specify a value for the Options argument of the MsgBox() function. Table 14.2 lists the values for each CommandButton set.

TABLE 14.2  Setting the Options Argument of the MsgBox() Function

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

The MsgBox() function is designed so that any combination of the icon constant and the CommandButton constant creates a unique value. This value is then broken down by the function to specify the individual pieces. The code used to create Figure 14.2 combines an icon constant and CommandButton constant to create an information message box with Yes, No, and Cancel buttons.

Setting a Default Button in a Message Box

If you're using more than one CommandButton in the message box, you can also specify which button is the default. The default button--which has the focus when the message box is displayed--is the one that users will most likely choose or that will be clicked if users automatically press Enter.

To specify which button is the default, you need to add another constant to the Options argument of the MsgBox() function:

Default Button Value Constant
First 0 vbDefaultButton1
Second 256 vbDefaultButton2
Third 512 vbDefaultButton3
Fourth 768 vbDefaultButton4

Evaluating a Return Value from the MsgBox() Function

You can choose from seven buttons, with the selection depending on the button set used in the message box. Each button, when clicked, returns a different value to your program (see Table 14.3).

TABLE 14.3  Return Values from the MsgBox() Function

Button Return Value Constant
OK 1 vbOK
Cancel 2 vbCancel
Abort 3 vbAbort
Retry 4 vbRetry
Ignore 5 vbIgnore
Yes 6 vbYes
No 7 vbNo

After you know which button the user clicked, you can use the information in your program. Listing 14.1 shows you code that uses the MsgBox() function to confirm whether to delete a file.


Hands-on project

The code for the MsgBox examples can be found in the project SimplMsg.vbp on the Web site dedicated to this book (http:// www.mcp.com/info). When you find that URL, enter 078971633x as the ISBN and then click Search to go to the Book Info page for Using Visual Basic 6.


LISTING 14.1  14LIST01.TXT--Deleting a File According to the Return from the
MsgBox() Function

01 Private Sub Command4_Click()
02 Dim strTextFile As String `path of file to delete
03 Dim Msg$ `Message box message
04 Dim OpVal% `Option value variable
05 Dim RetVal% `variable for return value
06 Dim TitleMsg$ `Title message variable
07
08 `Set the file to delete
09 strTextFile = "MYDATA.TXT"
10
11 `Create a message for the message box
12 Msg$ = "Do you really want to delete file: `"
13 Msg$ = Msg$ & strTextFile & "`?"
14
15 `Create a custom value for the Option parameter
16 OpVal% = vbExclamation + vbYesNo + vbDefaultButton2
17
18 `Create a title string
19 TitleMsg$ = "Delete Confirmation"
20
21 `Display the message box and get a return value
22 RetVal% = MsgBox(Msg$, OpVal%, TitleMsg$)
23
24 `If the value is Yes, set the commandButton
25 `caption to report that the Kill function has
26 `been selected
27 If RetVal% = vbYes Then
28 Command4.Caption = "Kill " & strTextFile
29 End If
30
31 End Sub

Using Predefined Forms

Visual Basic 6 comes with a number of predefined forms that can save you time in your coding activity. Visual Basic has predefined forms for data access, an About box, splash screens, and logins, to name a few.

Choose Add Form from the Project menu to display the dialog that contains the various predefined forms that ship with Visual Basic. Select the form that you want to use from this dialog (see Figure 14.4).

FIGURE 14.4 You can choose from predefined forms or a Form Wizard in the Add Form dialog.

If you need to add an About dialog to your project, click About Dialog in the Add Form dialog. (Figure 14.5 shows an About Dialog form.) Not only does Visual Basic add the form to your project, it also provides a substantial amount of code that covers the fundamental functionality of the form. The About Dialog provides code that reports that application's name and version information, as shown in the following code:

Private Sub Form_Load()
    Me.Caption = "About " & App.Title
    lblVersion.Caption = "Version " & App.Major & "." _
                         & App.Minor & "." & App.Revision
    lblTitle.Caption = App.Title
End Sub

The About dialog also provides all the code, including the external Windows API calls, that you need to report the user's system information. (If you want to review the system information code, add the About Dialog form to a new project and look at the code under the System Info button.)

FIGURE 14.5 The About dialog that ships with VB6 automatically provides code that reports your program's name and version information as well as the user's system information.

Getting User Input from the CommonDialog Control


Need the code?

The code for the CommonDialog control examples is in the project SimpleCD.VBP on the Web site dedicated to this book.


At some point you'll probably want to write a program in which your users can specify filenames, select fonts and colors, and control the printer. Although you could create your own dialogs to handle these tasks, you don't need to. Visual Basic provides you with the CommonDialog control, with which you can easily display predefined dialogs to obtain user information. Although the ease of setup is a great benefit, an even bigger bonus is that these dialogs are already familiar to users because they are the same dialogs used by Windows itself.

By using a single CommonDialog control, you have access to the following four Windows dialogs:

To use the CommonDialog control, you first have to add it to your project by selecting Microsoft Common Dialog Control 6.0 from the Components dialog (choose Components from the Project menu). After you add the CommonDialog control to your ToolBox, click the control and draw it on the form, like any other control. The CommonDialog control appears on your form as an icon; the control itself isn't visible when your application is running. However, when the code calls the CommonDialog, the specific dialog becomes visible.

The following sections discuss each type of dialog that can be accessed with the CommonDialog control. For each dialog, you must set the control's properties through the Properties window or through the CommonDialog control's Property Pages dialog. The Property Pages dialog provides you easy access to the specific properties necessary for each common dialog type (see Figure 14.6). You access the Property Pages dialog by clicking the ellipsis button in the Custom property of the CommonDialog control in the Properties window.

FIGURE 14.6 The CommonDialog control is visible at design time and can be configured by using the control's Property Pages.

Retrieving File Information with the File Dialog

A key use of the CommonDialog control is to obtain filenames from users in two ways: file open and file save. File-open mode lets users specify a file to be retrieved and used by your program. File-save mode lets users specify the name of a file to be saved (the equivalent of the Save As dialog for many programs). Figure 14.7 shows a dialog with the major components indicated.

The dialogs for the Open and Save functions are similar. To open an existing file, you use the ShowOpen method of the CommonDialog control. (This method displays the dialog shown in Figure 14.7.) You use this method by specifying the name of the CommonDialog control and the method name, as follows:

CommonDlg1.ShowOpen

FIGURE 14.7 The CommonDialog accesses the Windows file dialogs.

Running the CommonDialog control for saving a filename is essentially the same as for opening a file. In this case, however, the name of the method is ShowSave. There are a few subtle differences between the dialogs shown for the Open and Save functions, such as the title of the dialog and the captions on the buttons.

So far, you've learned how to display the File dialogs with all files shown in a folder. You might, however, want to specify that only certain file types, such as text or document files, be shown. The file types shown in the dialog are specified by using the CommonDialog control's Filter property. You set this property in design mode from the Property Pages dialog or set it at runtime with an assignment statement, as shown here:

controlname.Filter = "description|filtercond"

In this syntax,


Be careful with filter syntax

Don't include spaces before or after the pipe symbol. If you do, 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 quotation marks. Omit the quotation marks if you specify the filter from the Property Pages dialog.

You can specify multiple description|filtercond pairs within the Filter property. Each pair must be separated from the other pairs by the pipe symbol, as shown in the following example:

cdlgGetFile.Filter = "Text Documents|*.txt |All Files (*.*)|*.*"

The FileType combo box in Figure 14.7 shows the preceding code applied to the CommonDialog.

Finally, when all your filtering is set, you use the CommonDialog control's FileName property to retrieve the name of the file that users selected:

MyFileName$ = cdlgGetFile.FileName.

Retrieving a filename from a file

1. Open a New Visual Basic project.

2. Add CommonDialog controls as described earlier.

3. Add a CommondDialog control, CommandButton, and Label to the form.

4. Align the Label control so that it's above the CommandButton. Place both controls in the upper left corner of the form.

5. Double-click the CommandButton on the form to expose the Command1_Click event procedure.

6. Add the following code to the event procedure (leave out the line numbers):

01 CommonDialog1.Filter = "All Files (*.*)|*.*"
02 CommonDialog1.ShowOpen
03    If CommonDialog1.FileName <> "" Then
04        Label1.Caption = CommonDialog1.FileName
05    Else
06        Label1.Caption = "No file selected"
07    End If

This code works as follows:

Selecting Font Information with the Font Dialog

Setting up the CommonDialog control to show the Font dialog is as easy as setting it up for file functions. In fact, you can use the same CommonDialog control to handle file, font, color, and printer functions.


Using flags with the CommonDialog control

If you're using the CommonDialog control to select fonts and don't set a value for the Flags property, you will receive an error message stating that no fonts are installed.


The first step in using the CommonDialog control to handle font selection is to set a value for the Flags property. This property tells the CommonDialog control whether you want to show screen fonts, printer fonts, or both. The Flags property can be set to one of three constants:

Font Set Constant Value
Screen fonts cdlCFScreenFonts 1
Printer fonts cdlCFPrinterFonts 2
Both sets cdlCFBoth 3

Figure 14.8 shows a Font dialog that contains only screen fonts.

FIGURE 14.8 The Font common dialog lets the user select fonts.

You can set the value of the Flags property from the design environment by using the Property Pages dialog or from your program by using an assignment statement. After you set the Flags property, you can run the Font dialog from your code by using the ShowFont method, which has the same syntax as the ShowOpen method described earlier.

The information about the fonts chosen from the CommonDialog control is contained in the control's properties. Table 14.4 shows the control's properties and the font attributes that each manipulates.

TABLE 14.4  Control Properties That Store Font Attributes

Property Attribute
FontName The name of the base font
FontSize The height of the font in points
FontBold Whether boldface is selected
FontItalic Whether italic is 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 control in your program or even to set the font for the Printer object. The following code shows how the font information would be retrieved and used to change the fonts in the txtSample TextBox.

`cdlGetFont is the name of a common dialog
cdlGetFont.ShowFont
txtSample.FontName = cdlGetFont.FontName
txtSample.FontSize = cdlGetFont.FontSize
txtSample.FontBold = cdlGetFont.FontBold
txtSample.FontItalic = cdlGetFont.FontItalic
txtSample.FontUnderline = cdlGetFont.FontUnderline
txtSample.FontStrikethru = cdlGetFont.FontStrikethru

Selecting Colors with the Color Dialog

The CommonDialog control's Color dialog lets users select colors for the foreground or background of your forms or controls (see Figure 14.9). Users can choose a standard color or create and select a custom color.

FIGURE 14.9 The Color common dialog lets your users choose a color to use in the program.

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 call the ShowColor method.

When users select a color from the dialog, its color value is stored in the control's Color property. The following code shows how to change a form's background color through the Color dialog:

CommonDlg1.Flags = cdlCCRGBInit
CommonDlg1.ShowColor
Myform.BackColor = CommonDlg1.Color

Setting Printer Options with the Print Dialog

The CommonDialog control's Print dialog lets users select which printer to use for a print job and specify options for the print process. These options include specifying all pages, a range of pages, or the selection to print. There's also an option to specify the number of copies to be printed, as well as an option to print to a file.

To run the Print dialog, call the CommonDialog control's ShowPrinter method. No flags are set before the call.

In the Print dialog, users can select the printer from the Name list, which contains all printers installed in Windows. Below the Name list is the Status line, which tells you the current status of the selected printer.

The Print dialog returns the information from users in the dialog's properties. The FromPage and ToPage properties tell you the starting and ending pages of the selected printout. The Copies property tells you how many copies users want printed.

This is provided only as information. The Print dialog doesn't automatically set up the desired printout. In the Windows environment, the printer is considered to be nothing more than another output device and is treated programmatically the same as your computer monitor; there's no intelligence within your monitor that knows how to make a form or window. Your program does this and passes that output onto the monitor. The same is true with printing. Your program makes the output and then passes it onto the printer.

Making a Simple MDI Application

MDI is an acronym for Multiple Document Interface. An MDI application is one in which all windows of the application are enclosed in one containing window. Examples of an MDI application are Microsoft Word and Microsoft Excel (see Figure 14.10).

FIGURE 14.10 Microsoft Excel is an example of an MDI application.

Visual Basic has defined an MDI object named the MDIForm. A given VB application can contain only one MDIForm object but can have a multitude of other forms, some of which can be children of the MDIForm object and some of which can be independent, standalone windows. The child windows of an MDIForm don't contain their own menu. Instead, the child windows are controlled by the menu of their parent MDI form. If you add a menu to an MDI child form, at runtime it won't be visible within the MDI child form. The active child's menu appears on the parent window in place of the parent's menu.


Form and component naming

The forms and other components of the sample application have suggested names, but feel free to experiment and tailor the program to your needs.


Make a simple MDI application

1. Open a new project and name it SimplMDI.VBP.

2. Rename the project's default form to frmChild. Save the form file with the name frmChild.vbp.

3. From the Project menu, choose Add MDI Form to add an MDI form to your project. Rename the MDI form as mdiMain. Save the form file with the filename mdiMain.frm.

4. Set frmChild's MDIChild property to True to make the form a child of mdiMain.

5. Press Ctrl+E or click to open the Menu Editor.

6. Create a menu for the mdiMain form, as shown in Figure 14.11. Set the values of the Name and Caption properties of the menu and menu items, as shown in Table 14.5. Make sure that you select the WindowList CheckBox (on the middle right of the Menu Editor) for mnuWindow.

FIGURE 14.11 You make menus for an MDI application by using the Visual Basic Menu Editor.

TABLE 14.5  Object Captions and Names for the SimplMDI Menu

Caption Name Indent
&File mnuFile 0
&Add itmAdd 1
E&xit itmExit 1
&Window mnuWindow 0
&Cascade itmCascade 1
&Tile itmTile 1

7. From the Project menu, choose SimplMDI Properties. On the General page of the Project Properties dialog, select mdiMain from the Startup Object drop-down list (see Figure 14.12).

FIGURE 14.12 Choose the MDI form to be the startup form.

8. Between the lines Private Sub itmAdd_Click() and End Sub, add the code in Listing 14.2 (lines 2-9).

LISTING 14.2   14LIST02.TXT--The itmAdd_Click() Event Procedure

01 Private Sub itmAdd_Click()
02 Dim NewForm As New frmChild ` Declare another new form
03 Dim FormNum%
04 `Add it to the new form
05 Load NewForm
06 `Get a number for the new form, less the MDI parent
07 FormNum% = Forms.Count - 1
08 `Set its caption
09 NewForm.Caption = "I am MDI child: " + CStr(FormNum%)
10 End Sub
9. Between the lines Private Sub itmExit_Click() and End Sub, add the following code:

Un Load Me
10. Between the lines Private Sub itmCascade_Click() and End Sub, add the following code line:

Arrange vbCascade
11. Between the lines Private Sub itmTile_Click() and End Sub, add the following code line:

Arrange vbTileHorizontal
12. Compile and run the code.

The code for SimplMDI works this way: First you create a standard VB project and do some renaming. Then you add an MDI form to the project. You go back to the default form created when you originally made the project. You make it a child of the mdiMain MDI form by changing its MDIChild property to True. Then you open the Menu Editor and make a menu for the mdiMain form. You check the WindowsList check box for mnuWindow to enable the menu to list all open windows of an MDI form object. After the menu is created, you change the startup form. Then you add the event handlers for the menu items. Finally, you compile and run (see Figure 14.13).

FIGURE 14.13 The project SimplMDI shows you child forms within a MDI form.

The itmAdd_Click() event procedure dynamically creates a new form by using the New operator. The new form's caption has a number, FormNum%--added to the end of the string assigned to it--to indicate the order in which the child form was created. FormNum% is determined by polling the application to report all its forms using the Forms.Count property. After all the forms are determined, 1 is subtracted to account for the uniqueness of the application-only MDIForm object. Therefore, within the scope of this application, the resulting number must be the number of child forms the MDIForm object contains.

The application uses the MDIForm object's Arrange method in the itmCascade_Click() and itmTile_Click() event handlers. The Arrange method automatically positions child windows within an MDI window. The Arrange method takes an argument, arrangement, which can be set to one of the values in Table 14.6.

TABLE 14.6  Windows Arrange Settings

Constant Value Description
vbCascade 0 Cascades all nonminimized MDI child forms
vbTileHorizontal 1 Tiles all nonminimized MDI child forms horizontally
vbTileVertical 2 Tiles all nonminimized MDI child forms vertically
vbArrangeIcons 3 Arranges icons for minimized MDI

The Appearance Property

Users respond positively to forms with a three-dimensional (3D) style. Visual Basic allows you to make 3D forms by changing the Appearance property of an MDI form to 1 - 3D.

The AutoShowChildren Property


Using the Show method

If you have a form that loads data into itself, set the AutoShowChildren property to False and use the Show method. First, load the data into the form. Second, make sure that all the data loaded correctly. Last, show the form. If your form depends on the integrity of data, this process offers you the highest degree of reliability.


By default, the AutoShowChildren property is set to False. For this reason, unless you remember to use the Show method in your code to display the form after you load it, users will have to go through some sort of process to make the form visible. This can be a potential headache for you if you forget to use the Show method to display a newly loaded form. When you set AutoShowChildren to True, an MDI child form becomes visible when displayed through the Load statement. Doing this saves you programming time while also making your code more reliable.

MDI applications have become a very popular way to give a uniform appearance to applications. It wasn't too long ago that Visual Basic was an SDI (single-document interface) application in which all windows of the Visual Basic IDE existed independent of one another. Although making the VB IDE to be SDI is a configuration option, many developers find the MDI configuration an easier alternative and more in line with the rest of the Visual Studio initiative. Also, with more and more applications taking on the look and feel of Web browsers, making your program an MDI application might serve you well for applications that require more than one window.


Previous chapterNext chapterContents

© Copyright, Macmillan Computer Publishing. All rights reserved.