Microsoft Visual Basic 2010 Step by Step eBook

(Tina Meador) #1

Chapter 17 Working with Printers 417


Your form looks similar to this:

Now add the program code necessary to print a graphic file (bitmap, icon, metafile,
JPEG file, and so on).


  1. Double-click the Print Graphics button.


The Button1_Click event procedure appears in the Code Editor.


  1. Move the insertion point to the top of the form’s code, and then type the following
    program statement:
    Imports System.Drawing.Printing
    This Imports statement declares the System.Drawing.Printing namespace, which makes
    it easier to reference the printing classes.

  2. Now move the insertion point down to the Button1_Click event procedure, and enter
    the following program code:
    ' Print using an error handler to catch problems
    Try
    AddHandler PrintDocument1.PrintPage, AddressOf Me.PrintGraphic
    PrintDocument1.Print() 'print graphic
    Catch ex As Exception 'catch printing exception
    MessageBox.Show("Sorry--there is a problem printing", ex.ToString())
    End Try


Note After you enter this code, you’ll see a jagged line under Me.PrintGraphic indicating
an error. Don’t worry, you’ll be adding the PrintGraphic procedure in the next step.

This code uses the AddHandler statement, which specifies that the PrintGraphic event
procedure (also called an event handler) should be called when the PrintPage event
of the PrintDocument1 object fires. An event procedure is a mechanism that handles
Free download pdf