Incorporate Windows Dialog Box Functionality in Your Applications
MICROSOFT OFFICE DEVELOPER EDITION
Incorporate Windows Dialog Box Functionality in Your Applicationsby Sean Kavanagh
There's a good chance you've found yourself in situations where your application would benefit from using existing Windows dialog boxes. For instance, when you require users to input filenames, having the ability to browse for the files on a hard drive saves time and ensures accuracy over typing the path and filename information in a text box. However, unlike other applications in the Office family, Access doesn't provide a straightforward way to use such a dialog box.
There are a number of ways to leverage Windows' built-in dialog boxes in your Access applications. One way is to make calls to the Windows API. Making API calls is easier to do than you might expect, but if you have one of the developer versions of Office on your system, you can take advantage of an ActiveX control that's even easier to use. In this article, we'll look at working with the ActiveX common dialog control, which presents an interface to several standard Windows dialog boxes. In a follow-up article, we'll look at how to incorporate dialog boxes by directly making API calls.
Accessing Windows' dialog boxesThe common dialog control is provided through COMDLG32.OCX and lets you use methods to display the Windows dialog boxes listed in Table A. This ActiveX control is available through the developer editions of Office or Visual Basic. You can use the information returned through the control's properties to perform such tasks as identifying files to manipulate, changing font attributes, or altering an object's color settings. In addition to the listed dialog boxes, the common dialog control supports the ShowHelp method, which allows you to display specific help entries through the Windows Help Engine.
Table A: Common dialog control methods to display dialog boxes
An important aspect of the common dialog control you need to understand is that, for the most part, the dialog boxes it displays don't perform any specific action--they simply collect information. For instance, if you select a file with the Open dialog box, clicking the Open button doesn't actually open the file. Doing so merely captures the path and filename information of the file you selected. To really open the file, you must add code to specifically do so.
Although this might seem to require extra work than should be needed, this behavior has advantages. For instance, you can use the Open dialog box to select a file, but then perform a different action, such as importing data into the current database or changing the data source for linked tables. The exception to this behavior is the Print dialog box. When you make a printer selection through the dialog box and click OK, that change is immediately reflected throughout your Windows programs.
Drawbacks of the controlIf the common dialog control is so easy to use, you're probably wondering why anyone would go to the trouble of making Windows API calls. First, as previously mentioned, you need a true development environment to have licensing rights to incorporate the OCX in your applications. Although you may have COMDLG32.OCX registered on your system, you'll be unable to add it to an application if you're just running Access without the developer tools available for your version of Office.
Another problem with the control is that you can run into problems with missing library references or version conflicts when you distribute your application. For instance, Visual Basic 6.0 uses a newer version of COMDLG32.OCX than the Office 97 Developer Edition Tools. If you have VB6, or a program built with VB6, installed on your system you'll also have the newer version of the OCX installed. If you develop an Access application and send it to someone that has the older version of the OCX, he'll receive an error when Access references the control. Likewise, it's possible that other users won't have the OCX registered on their systems at all. However, we'll look at steps you can take to minimize problems when you distribute your application.
Display basic dialog boxes with the common dialog controlTo illustrate how to incorporate Windows dialog boxes in an application, we'll create a simple form that let's you test the common dialog control's basic performance. The form will contain several command buttons that you'll use to access the various dialog boxes. We'll show you how to retrieve filename information about an existing file and how to capture user input for the purpose of naming and creating a new file. In addition, we'll record font and color settings, as you might want to allow users to customize your application's interface. Finally, we'll show you how to set printer options through the Print dialog box. Note that we'll focus on working with the dialog boxes--this article won't walk through the steps of actually opening or creating files.
To create your form, open an Access database and select Form from the New Object button's dropdown menu. Then, double-click on Design View in the New Form dialog box. Ensure that the Control Wizards button is not selected and add the command button, label and text box controls shown in Figure A, sizing and setting the control captions as appropriate.
Figure A: We'll use the command buttons on this form to launch different Windows dialog boxes.
Once you've added the controls, select the topmost command button and display its Property sheets. Set the control's Name property to cmdOpen. Then, select the next button down and name it cmdSaveAs. Rename the first textbox control txtImport and the second one txtExport. Next, rename the label control in the middle of the form lblPreview and set its Back Style property to Normal. Finally, name the remaining buttons cmdFont, cmdColor and cmdPrinter.
Adding the common dialog controlThe only control that's left to add is our common dialog control, which is a multipurpose object. By using the previously discussed methods and setting particular properties, a single control object is able to provide access to any or all of the possible Windows dialog boxes available through the common dialog control. In fact, as we'll discuss later, the common dialog control doesn't even need to be physically added to a form to take advantage of it. For now, though, we'll go through the process of actually incorporating one in a form.
To add the control, click the More Controls button on the Toolbox. Then, scroll through the list of available controls until you find Microsoft Common Dialog Control, followed by version information. Select the control and then use your mouse to draw a small control on the form's blank area. Regardless of the size you draw, the control will be resized to a small square icon . Using the control's Property sheet, change its name to cdlgExamples. Finally, set your form's Caption property to Common Dialog Box Examples and save the form as frmDialogs.
Manipulating dialog boxes with codeNow, let's add the code that displays the dialog boxes. First, click the Code button on the Form Design toolbar. Before entering any code, choose Tools | References from the menu bar and ensure that the Microsoft Common Dialog Control is selected. Once you've verified that the library reference is in place, dismiss the References dialog box.
The Open dialog boxThe first procedure we'll create displays the standard dialog box you use to select a file that you want to open. First, press [Ctrl][End] to move your insertion point to the end of the existing code. Then, enter the procedure shown in Listing A.
Now, let's examine the code. Keep in mind that our examples only use some of the properties available to the common dialog control. However, we've incorporated the ones we think you'll benefit from the most. The first thing to notice in this procedure is the way that we declared and set our
cdlg. In particular, note that when you set the variable, you must set it equal to the form control's
Listing A: Procedure to display the Open dialog box
The properties we set apply to both Open and Save As dialog boxes. In fact, other than the fact that some of the dialog box controls are labeled differently, the Open and Save As dialog boxes are essentially the same. The first property,
Private Sub cmdOpen_Click()Dim cdlg As CommonDialog On Error GoTo ErrorHandling Set cdlg = Me.cdlg Examples.ObjectWith cdlg.DialogTitle = "Locate Data".Filter = "Excel Workbook|*.xls|Access Database|*.mdb".FilterIndex = 2.CancelError = True.ShowOpenMe.txtImport = .FileName End WithSet cdlg = Nothing Exit SubErrorHandling:If Err = 32755 Then Exit SubElse MsgBox Err & ": " & Err.Description End If End Sub
DialogTitle, sets the text appearing in the dialog box's title bar. The next property,
Filter, defines what choices appear in the Files Of Type or Save As Type dropdown lists that let users limit which filenames appear for selection. As you can see, you use the pipe symbol (|) to separate file type descriptions from their extensions. It's important that you don't include extra spaces around the pipe symbol, as this will throw off how Access interprets the extensions.
FilterIndex property allows you to specify which file type filter is used by default. The entries specified by the
Filter property are indexed beginning with the number 1. As you can see from our code, our filter specifies two types of files: Excel workbooks and Access databases. The items in the Files Of Type dropdown list appear in the same order that they're entered in the
Filter property. Therefore, our
FilterIndex of 2 displays the Access Database choice by default.
We set the
CancelError property equal to
True to cause an error to be raised if the user closes the dialog box by clicking Cancel or the Close button. The error number returned is 32755, which we trap for in our error handling. In our case, we simply exit the procedure if the user dismisses the dialog box without clicking the Open button. After displaying the dialog box with the
ShowOpen method, assuming the Open button was clicked, we set the value of txtImport equal to the common dialog control's
FileName property, which is the full path and filename of the selected file. Remember, Access won't automatically open the selected file--we would need to add more code to accomplish that in a real-world application.
The Save As dialog boxNow, let's add procedures that show how to work with the other dialog boxes provided through the COMDLG32.OCX. In order to keep the length of the code down, we'll dispense with any additional error checking. Likewise, we'll only use object variables where they'll significantly improve our code.
At this point, add the procedure shown in Listing B, which displays the Save As dialog box. If a user enters a filename in the Save As dialog box without specifying a file extension, the
DefaultExt property setting will automatically be appended to the filename. Note that if the user has selected a Save As Type filter, the appropriate extension will automatically be used.
Listing B: Procedure to display the Save As dialog box
We incorporate another new property in this procedure,
Private Sub cmdSaveAs_Click()With Me.cdlgExamples.DialogTitle = "Save Your Data".DefaultExt = "xls".CancelError = False .Flags = cdlOFNOverwritePrompt + _ cdlOFNPathMustExist + cdlOFNHideReadOnly.ShowSaveMe.txtExport = .FileTitleEnd WithEnd Sub
Flagsproperty applies to all of the dialog box types and lets you modify a dialog box's appearance or functionality. In this case, we've used several intrinsic constants to modify the Save As dialog box. The constant
cdlOFNOverwritePromptforces the user to provide positive confirmation if he attempts to save to a filename that already exists. The next constant,
cdlOFNPathMustExist, requires that the path the user is saving to through the dialog box already exists. As you probably expect,
cdlOFNHideReadOnlyprevents the Open As Read Only check box from appearing on the dialog box.
The final new property we look at is
FileTitle. This property returns just the name of the file selected in the dialog box, without any of the path information. As before, we simply return the property value to a form text box so that you can examine the dialog box functionality.
The Color and Font dialog boxesChances are you may not have as much need for the Color and Font dialog boxes as the Open and Save As dialog boxes. However, they shouldn't be overlooked as you can use them to easily provide customization capabilities within your application. To illustrate, we'll use these two dialog boxes to modify the appearance of the large label control on our form. To add the code we'll use to work with the Font and Color dialog boxes, enter the code shown in Listing C.
The properties returned by the Color and Font dialog boxes are fairly obvious. The
Color property returns a
Long number value and the font properties are comparable to typical form control font properties. The major statement of note is the line that sets the Font dialog box's
Flags property. In the case of the Font dialog box, you must specify whether to display screen fonts, printer fonts or both. The intrinsic constants for those settings are
cdlCFBoth. Failure to set one of those flags will result in an error when you display the Font dialog box.
Listing C: Code to display the Color and Font dialog boxes
Private Sub cmdColor_Click()With Me.cdlgExamples.CancelError = False .ShowColorMe.lblPreview.BackColor = .ColorEnd With End Sub Private Sub cmdFont_Click()Dim cdlg As CommonDialog On Error Resume NextSet cdlg = Me.cdlgExamples.ObjectWith cdlg.CancelError = False .Flags = cdlCFScreenFonts.ShowFontEnd WithWith Me.lblPreview.FontName = cdlg.FontName.FontBold = cdlg.FontBold.FontItalic = cdlg.FontItalic.FontSize = cdlg.FontSize.FontUnderline = cdlg.FontUnderline End With Set cdlg = Nothing End Sub
The Print dialog boxTo display the Print dialog box, enter the code shown in Listing D. We kept this procedure very simple, but there are additional properties available that let you set or return printer options. For example, the
Copiesproperty can be used to set or return the number of copies of a printout to produce. The
ToPageproperties can be used to print a specific series of pages from a document. Note that in order to use the
ToPageproperties you must first set the
Minproperty represents the smallest number possible in the From text box and the
Maxproperty sets the largest acceptable number for the To text box.
Listing D: Code to display the Print dialog box
Private Sub cmdPrinter_Click() With Me.cdlgExamples.CancelError = False .ShowPrinter End With End Sub
Testing the dialog boxesWe've set up all the code for the dialog boxes, so let's test the results. First, save and close the form's class module. Then, switch to Form view and experiment with the dialog boxes. As you can see in Figure B, we successfully captured and applied font, color and filename information.
Figure B: We used common dialog box properties to set text box and label attributes.
Displaying common dialog boxes without form controls
As we mentioned earlier, you don't have to have a common dialog form control in place to display dialog boxes with COMDLG32.OCX. As long as a module has a reference set up to the OCX, you can simply use object variables to display the dialog boxes. For instance, you can display the Color dialog box using just the following code:
Private Sub GetColorValue() Dim cdl As New CommonDialog cdl.ShowColor End Sub
Avoiding OCX reference errorsBy including the COMDLG32.OCX as part of your application's standard installation, you can minimize problems that arise when the users you're developing for have inconsistent Windows systems. Rather than distributing a stand-alone Access file, use the Office Developer Edition's Setup Wizard to install and register the OCX with applications that use the common dialog control. To do so, click the Add button on the second screen of the wizard, navigate to the Windows\System folder and add COMDLG32.OCX. Access will automatically include the dependent file ComCat.dll.
An easy-to-code solutionThe common dialog control tends to get a bad rap due to the issues involved with version compatibility. However, it's easy to use, quick to implement and is appropriate in many situations. We'll examine the alternatives to it using the Windows API, but you shouldn't outright dismiss this helpful control.
Copyright © 2001 Element K Content LLC. All rights reserved. Reproduction in whole or in part in any form or medium without express written permission of Element K Content LLC is prohibited. Element K is a service mark of Element K LLC.