This example shows you how to use the Common Dialog control to display the Open, Save, Select Colour and Print dialog boxes.
First, add a Common Dialog control to your form (you will need to add the component to your project first by going to Project | Components) . Next, add a text box, and name it txtData. You now need to add some buttons to display the different dialog boxes. Name them cmdOpen, cmdSave, cmdColour, and cmdPrint, and set their captions appropriately. Finally, add the code below.
Private Sub cmdColour_Click()
On Error GoTo errhandler
CommonDialog1.CancelError = True
' Display the Colour dialog box
CommonDialog1.ShowColor
' Set the forms background colour to the one selected
Me.BackColor = CommonDialog1.Color
Exit Sub
errhandler:
Select Case Err
Case 32755 ' Dialog Cancelled
MsgBox "you cancelled the dialog
box"
Case Else
MsgBox "Unexpected error. Err
" & Err & " : " & Error
End Select
End Sub
Private Sub cmdOpen_Click()
On Error GoTo errhandler
CommonDialog1.CancelError = True
' Set flags
CommonDialog1.Flags = cdlOFNHideReadOnly +
cdlOFNPathMustExist + cdlOFNFileMustExist
' Set filters
CommonDialog1.Filter = "All Files (*.*)|*.*|RTF
(*.rtf)|*.rtf|Text Files (*.txt)|*.txt"
' Display the Save dialog box
CommonDialog1.Filename = ""
CommonDialog1.ShowOpen
txtData.Text = "File Selected: " &
CommonDialog1.Filename
Exit Sub
errhandler:
Select Case Err
Case 32755 ' Dialog Cancelled
MsgBox "you cancelled the dialog
box"
Case Else
MsgBox "Unexpected error. Err
" & Err & " : " & Error
End Select
End Sub
Private Sub cmdPrint_Click()
StopPrinting = False
' Set CancelError is True
On Error GoTo errhandler
CommonDialog1.PrinterDefault = True
CommonDialog1.CancelError = True
' Set flags
CommonDialog1.Flags = cdlPDReturnDC + cdlPDNoPageNums
CommonDialog1.ShowPrinter
Printer.Print txtData.Text
Printer.EndDoc
Exit Sub
errhandler:
Select Case Err
Case 32755 ' Dialog Cancelled
MsgBox "you cancelled the dialog
box"
Case Else
MsgBox "Unexpected error. Err
" & Err & " : " & Error
End Select
End Sub
Private Sub cmdSave_Click()
On Error GoTo errhandler
CommonDialog1.CancelError = True
' Set flags
CommonDialog1.Flags = cdlOFNHideReadOnly +
cdlOFNOverwritePrompt + cdlOFNPathMustExist
' Set filters
CommonDialog1.Filter = "All Files (*.*)|*.*|RTF
(*.rtf)|*.rtf|Text Files (*.txt)|*.txt"
' Specify default filter
' Display the Save dialog box
CommonDialog1.Filename = ""
CommonDialog1.ShowSave
' Set the label values
txtData.Text = "File Selected: " &
CommonDialog1.Filename
Exit Sub
errhandler:
Select Case Err
Case 32755 ' Dialog Cancelled
MsgBox "You cancelled the dialog
box"
Case Else
MsgBox "Unexpected error. Err
" & Err & " : " & Error
End Select
End Sub
Comments