Allowing Printer Selection
If you have multiple printers connected to your computer, it makes sense for the user to choose a particular printer to print to instead of sending it directly to the default printer. You can do so using the PrintDialog class.
Modify the
Else clause near the end of the Print button's
Click event to show a dialog window that allows users to choose a printer.
Private Sub btnPrint_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles btnPrint.Click, btnPreview.Click
Dim printDoc As New PrintDocument()
AddHandler printDoc.BeginPrint, _
New PrintEventHandler(AddressOf Me._beginPrint)
AddHandler printDoc.PrintPage, _
New PrintPageEventHandler( _
AddressOf Me._printPage)
If CType(sender, Button).Text = "Preview" Then
'---show preview---
Dim dlg As New PrintPreviewDialog()
dlg.Document = printDoc
dlg.ShowDialog()
 | |
| Figure 13. Picky Printing: Having added print selection functionality, the user can now can select a printer using the PrintDialog class. |
Else
Dim pd As New PrintDialog
pd.Document = printDoc
pd.AllowSomePages = True
Dim result As DialogResult = pd.ShowDialog()
If result = Windows.Forms.DialogResult.OK Then
printDoc.Print()
End If
End If
End Sub
Figure 13 shows the Print dialog window when the user clicks on the Print button.
There are several properties that allow you to extract the settings selected in the Print window (such as print range, copies, etc). The following shows some useful properties:
- pd.PrinterSettings.CopiesNumber of copies to print
- pd.PrinterSettings.FromPageThe first page to print
- pd.PrinterSettings.ToPageThe last page to print
The Fine Print
In this article, you have seen how simple it is to print from your Windows-based application. The PrintDocument class encapsulates many of the gory details involved in printing from your application, letting you concentrate on the
PrintPage event, where you write the logic to format your output and it to the printer. With this newfound knowledge, you have no more excuses for building applications that lack printing support!