Microsoft Visual Basic 2010 Step by Step eBook

(Tina Meador) #1

422 Part III Designing the User Interface



  1. Now scroll back down to the Button1_Click event procedure, and then enter the
    following program code:


' Print using an error handler to catch problems
Try
' Declare PrintDoc variable of type PrintDocument
Dim PrintDoc As New PrintDocument
AddHandler PrintDoc.PrintPage, AddressOf Me.PrintText
PrintDoc.Print() 'print text
Catch ex As Exception 'catch printing exception
MessageBox.Show("Sorry--there is a problem printing", ex.ToString())
End Try
The lines that are new or changed from the Print Graphics program are shaded. Rather
than add a PrintDocument control to your form, this time you simply created the
PrintDocument programmatically by using the Dim keyword and the PrintDocument
type, which is defined in the System.Drawing.Printing namespace. From this point on,
the PrintDoc variable represents the PrintDocument object, and it is used to declare the
error handler and to print the text document. Note that for clarity, I renamed the Sub
procedure that will handle the print event PrintText (rather than PrintGraphic).


  1. Scroll above the Button1_Click event procedure in the Code Editor to the general
    declaration area. Type the following PrintText event procedure:


'Sub for printing text
Private Sub PrintText(ByVal sender As Object, _
ByVal ev As PrintPageEventArgs)
'Use DrawString to create text in a Graphics object
ev.Graphics.DrawString(TextBox1.Text, New Font("Arial", _
11, FontStyle.Regular), Brushes.Black, 120, 120)
' Specify that this is the last page to print
ev.HasMorePages = False
End Sub
This routine handles the printing event generated by the PrintDoc.Print method. The
changes from the PrintGraphic procedure in the previous exercises are also shaded. As
you can see, when you print text, you need to use a new method.
Rather than use Graphics.DrawImage, which renders a graphics image, you must
use Graphics.DrawString, which prints a text string. I’ve specified the text in the Text
property of the text box object to print some basic font formatting (Arial, 11 point,
regular style, black color), and (x, y) coordinates (120, 120) on the page to start
drawing. These specifications will give the printed output a default look that’s similar
to the text box on the screen. Like last time, I’ve also set the ev.HasMorePages
property to False to indicate that the print job doesn’t have multiple pages.


  1. Click the Save All button on the toolbar to save your changes, and then specify
    C:\Vb10sbs\Chap17 as the folder location.

Free download pdf