The Open dialog box allows the user to specify a drive, a directory, a file name extension, and a file name.
The Save As dialog box is identical to the Open dialog in appearance, except for the dialog's caption, and file names appearing dimmed out. At run time, when the user chooses a file and closes the dialog box, the FileName property is used to get the selected file name.
Figure 7.12 An Open dialog box
To display the Open dialog box
You can do this by setting the Filter property using the following format:
description1 | filter1 | description2 | filter2...
Description is the string displayed in the list box — for example, "Text Files (*.txt)." Filter is the actual file filter — for example, "*.txt." Each
description | filter set must be separated by a pipe symbol (|).
After the user chooses a file, use the FileName property to get the name of the selected file.
With all the common dialog boxes, when the CancelError property is True, an error is generated when the user clicks the dialog box's Cancel button. You detect that the Cancel button was pressed by trapping the error when the dialog box is displayed.
The following code displays an Open dialog box and uses the selected file name as an argument to a procedure that opens a file:
Private Sub mnuFileOpen_Click ()
' CancelError is True.
On Error GoTo ErrHandler
' Set filters.
CommonDialog1.Filter = "All Files (*.*)|*.*|Text _
Files (*.txt)|*.txt|Batch Files (*.bat)|*.bat"
' Specify default filter.
CommonDialog1.FilterIndex = 2
' Display the Open dialog box.
CommonDialog1.ShowOpen
' Call the open file procedure.
OpenFile (CommonDialog1.FileName)
Exit Sub
ErrHandler:
' User pressed Cancel button.
Exit Sub
End Sub