Managing Printing in Your .NET Application
Pages: 1, 2, 3, 4
Selecting a Printer
If you have multiple printers attached to your computer, it is a good idea to let the user choose the desired printer instead of sending the output to the default printer. You can do so via the PrintDialog class, which is demonstrated below:
Private Sub btnPrint_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnPrint.Click
'---let user select a printer to print---
Dim pd As New PrintDialog
With pd
.Document = printDoc
.AllowSomePages = True
End With
Dim result As DialogResult = pd.ShowDialog()
If result = Windows.Forms.DialogResult.OK Then
printDoc.Print()
End If
End Sub
Figure 7 shows how the PrintDialog class looks like when it is shown.

Figure 7. Letting the user choose a printer to which to print
You can set some default values for the PrintDialog class, such as the following properties in bold:
Dim pd As New PrintDialog
With pd
.Document = printDoc
.AllowSomePages = True
.PrinterSettings.Copies = 3
.PrinterSettings.FromPage = 2
.PrinterSettings.ToPage = 5
End With
Figure 8 shows the default values set.

Figure 8. Printer selection dialog with some default values set
Notifying the User When Printing Completes
It is always a good practice to inform the user when the printing is completed. To do so, simply display a message in the EndPrint event handler, such as the following:
Private Sub _endPrint( _
ByVal sender As Object, _
ByVal e As PrintEventArgs)
'---de-reference the fonts---
f_title = Nothing
f_body = Nothing
MessageBox.Show(printDoc.DocumentName & _
" has finished printing.")
End Sub
Configuring the Page Setup
Besides letting the user choose the printer to print to, it would also be useful to let users configure the page setup so that he can choose the page details, such as page orientation, paper size, etc. To demonstrate this, add a Button control to the page (see Figure 9) and code it as shown below:

Figure 9. Adding a Page Setup Button control
Private Sub btnPageSetup_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles btnPageSetup.Click
Dim pageSetup As New PageSetupDialog
With pageSetup
.PageSettings = printDoc.DefaultPageSettings
.ShowDialog()
End With
End Sub
Figure 10 shows how the PageSetupDialog class looks like when shown.

Figure 10. Configuring Page Setup
Summary
In this article, you have seen the main steps in enabling printing in your Windows application. Does your application support printing? Use the talkback links below to share your thoughts with our readers.
Wei-Meng Lee (Microsoft MVP) http://weimenglee.blogspot.com is a technologist and founder of Developer Learning Solutions http://www.developerlearningsolutions.com, a technology company specializing in hands-on training on the latest Microsoft technologies.
Return to Windows DevCenter.

