Microsoft Visual Basic 2010 Step by Step eBook

(Tina Meador) #1

Chapter 17 Working with Printers 427


Add code for the btnPrint and PrintDocument1 objects


  1. Display the form again, and then double-click the Print button (btnPrint) to display its
    event procedure in the Code Editor.

  2. Type the following program code:


Try
'Specify current page settings
PrintDocument1.DefaultPageSettings = PrintPageSettings
'Specify document for print dialog box and show
StringToPrint = RichTextBox1.Text
PrintDialog1.Document = PrintDocument1
Dim result As DialogResult = PrintDialog1.ShowDialog()
'If click OK, print document to printer
If result = DialogResult.OK Then
PrintDocument1.Print()
End If
Catch ex As Exception
'Display error message
MessageBox.Show(ex.Message)
End Try
This event procedure sets the default print settings for the document and assigns the
contents of the RichTextBox1 object to the StringToPrint string variable (defined at the
top of the form) in case the user changes the text in the rich text box. It then opens
the Print dialog box and allows the user to adjust any print settings (printer, number of
copies, the print-to-file option, and so on). If the user clicks OK, the event procedure
sends this print job to the printer by issuing the following statement:

PrintDocument1.Print()


  1. Display the form again, and then double-click the PrintDocument1 object in the
    component tray.
    Visual Studio adds the PrintPage event procedure for the PrintDocument1 object.

  2. Type the following program code in the PrintDocument1_PrintPage event procedure:


Dim numChars As Integer
Dim numLines As Integer
Dim stringForPage As String
Dim strFormat As New StringFormat
'Based on page setup, define drawable rectangle on page
Dim rectDraw As New RectangleF( _
e.MarginBounds.Left, e.MarginBounds.Top, _
e.MarginBounds.Width, e.MarginBounds.Height)
'Define area to determine how much text can fit on a page
'Make height one line shorter to ensure text doesn't clip
Dim sizeMeasure As New SizeF(e.MarginBounds.Width, _
e.MarginBounds.Height - PrintFont.GetHeight(e.Graphics))

'When drawing long strings, break between words
strFormat.Trimming = StringTrimming.Word
Free download pdf