Chapter 17 Working with Printers 433
- Type the following program code:
Try
'Specify current page settings
PrintDocument1.DefaultPageSettings = PrintPageSettings
'Specify document for print preview dialog box and show
StringToPrint = RichTextBox1.Text
PrintPreviewDialog1.Document = PrintDocument1
PrintPreviewDialog1.ShowDialog()
Catch ex As Exception
'Display error message
MessageBox.Show(ex.Message)
End Try
In a similar way, the btnPreview_Click event procedure assigns the PrintPageSettings
variable to the DefaultPageSettings property of the PrintDocument1 object, and then
it copies the text in the rich text box object to the StringToPrint variable and opens the
Print Preview dialog box. Print Preview automatically uses the page settings data to
display a visual representation of the document as it will be printed—you don’t need to
display this information manually.
Now you’ll make a slight modification to the program code in the btnOpen_Click event
procedure.
- Scroll up to the btnOpen_Click event procedure in the Code Editor.
This is the procedure that displays the Open dialog box, opens a text file, and enables
the printing buttons. Because you just added the Page Setup and Print Preview
buttons, you have to add program code to enable those two printing buttons as well.
- Scroll to the bottom of the event procedure, just before the final Catch code block,
and then locate the following program statement:
btnPrint.Enabled = True
- Below that statement, add the following lines of code:
btnSetup.Enabled = True
btnPreview.Enabled = True
Now your program will enable the print buttons when there’s a document available
to print.
- Click the Save All button on the toolbar to save your changes.
Test the Page Setup and Print Preview features
Tip The complete Print Dialogs program is located in the C:\Vb10sbs\Chap17\Print
Dialogs folder.