3.4. Printing a Document


One of the key features of any full-fledged desktop application is the ability to print. Let's add another choice to the Welcome Form menu, mnuFile with the text File. While creating the menu choice, use the Properties window to create mnuFile_Click and add a single line:

 Private Sub mnuFile_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles mnuFile.Click    frmText.Show(  ) End Sub 

As you can guess, you'll now want to add a new form, frmText to the project. Resize the new form to 700,600 and set its text attribute to "Text Form."

This form will have two controls, a RichTextBox and a menu. The menu name will be "File" (mnuFile) and will have sub-menu items of Open, Save, and Print, as shown in Figure 3-14.

Figure 3-14. Items Collection Editor Items Collection Editor


After your menu is set up, drag a RichTextBox control onto the form and set its size to 668,512 and its location to 12,42.

Drag an OpenFileDialog and a SaveFileDialog onto your tool strip, along with a PrintDocument and a PrintDialog control, leaving their default names as they are. Implement the mnuFileOpen_Click event handler first, as shown in Example 3-15.

Example 3-15. File menu Open item Click event handler
 Private Sub mnuFileOpen_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles mnuFileOpen.Click     ' set the initial directory in which to look for files     Me.OpenFileDialog1.InitialDirectory = "C:\Temp"     'set the file filter     Me.OpenFileDialog1.Filter = "Text files (*.txt) | *.txt"     ' check to see if the user clicked ok, if so, load the     ' file into the rich text box, setting the file type to     ' plain text, and set the font     Dim result As DialogResult = Me.OpenFileDialog1.ShowDialog(  )     If result = Windows.Forms.DialogResult.OK Then         RichTextBox1.LoadFile( _             OpenFileDialog1.FileName, _             RichTextBoxStreamType.PlainText)         RichTextBox1.SelectionFont = New Font("Verdana", 10)     End If End Sub 

The File Save dialog box works just like the file save you saw for the Active Document example. When the user clicks save on the menu, the mnuFilesSave_Click event is raised. The event handler displays the SaveFileDialog, as shown in Example 3-16.

Example 3-16. Save menu item Click event handler
 Private Sub mnuFilesSave_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles mnuFilesSave.Click     Me.SaveFileDialog1.FileName = _        Me.OpenFileDialog1.FileName     Me.SaveFileDialog1.Filter = _        Me.OpenFileDialog1.Filter     Me.SaveFileDialog1.ShowDialog(  ) End Sub 

When the user clicks OK in the dialog, the SaveFileDialog's FileOK event is raised, and handled in your handler by writing the file to disk, as shown in Example 3-17. Notice that the RichTextBox control knows how to do this.

Example 3-17. File dialog OK event handler
 Private Sub SaveFileDialog1_FileOk( _ ByVal sender As System.Object, _ ByVal e As System.ComponentModel.CancelEventArgs) _ Handles SaveFileDialog1.FileOk     Me.RichTextBox1.SaveFile( _         Me.SaveFileDialog1.FileName, _         RichTextBoxStreamType.RichText) End Sub 

3.4.1. Handling the Print Click Event

The print Click event handler is a bit more complicated. You will break the logic into two methods: the event handler for the menu choice, and the event handler for the PrintDocument object you've added to your page. Because you will need to create the Stream object for the document in the Print event handler, and you'll need to reference that stream in the PrintDocument's PrintPage event handler, you'll create a member variable for the class to hold that stream.

 Public Class frmText     Private streamToPrint As StringReader 

To identify the string reader, you'll add the following to the top of the file:

 Imports System.IO 

When the user clicks on the Print menu choice, the event handler initializes streamToPrint by creating a new StringReader with the text from the RichTextBox:

 streamToPrint = New StringReader(Me.RichTextBox1.Text) 

The PrintDialog is shown, allowing the user to pick a printer and set its characteristics:

 Me.PrintDialog1.Document = PrintDocument1 Dim dlgResult As DialogResult = Me.PrintDialog1.ShowDialog(  ) 

If the user clicks OK, the PrintDocument's Print method is called, which raises the PrintPage event on that object, as shown in Example 3-18.

Example 3-18. Raising the PrintPage event
 If dlgResult = Windows.Forms.DialogResult.OK Then    Try       PrintDocument1.Print(  )    Catch ex As Exception       MessageBox.Show("error printing " + ex.Message)    Finally       streamToPrint.Close(  )    End Try End If 

When the PrintPage event is raised, the PrintDocument's event handler is called, as shown in Example 3-19.

Example 3-19. Print menu item PrintPage event handler
 ' called from mnuFilePrint_Click Private Sub PrintDocument1_PrintPage( _ ByVal sender As System.Object, _ ByVal e As System.Drawing.Printing.PrintPageEventArgs) _ Handles PrintDocument1.PrintPage    Dim printFont As Font = New Font("Verdana", 10)    Dim linesPerPage As Single = 0    Dim yPosition As Single = 0    Dim ctr As Integer = 0    Dim left As Single = e.MarginBounds.Left    Dim top As Single = e.MarginBounds.Top    Dim line As String = Nothing    ' Calculate the number of lines per page.    linesPerPage = e.MarginBounds.Height / _        printFont.GetHeight(e.Graphics)    While ctr < linesPerPage       line = streamToPrint.ReadLine(  )       If line Is Nothing Then          Exit While       End If       yPosition = top + ctr * _           printFont.GetHeight(e.Graphics)       e.Graphics.DrawString  ( _       line, _       printFont, _       Brushes.Black, _       left, _       yPosition, _       New StringFormat(  ))       ctr += 1    End While    If line IsNot Nothing Then       e.HasMorePages = True    Else       e.HasMorePages = False    End If End Sub 

The second argument passed in is of type PrintPageEventArgs, which contains vital information about how to print the page.

For simplicity you'll hardcode a font (Verdana, 10 point) to print with, using the following declaration:

 Dim printFont As Font = New Font("Verdana", 10) 

With that font in hand, you can compute the number of lines per page:

 linesPerPage = e.MarginBounds.Height / _     printFont.GetHeight(e.Graphics) 

That done, you can begin reading lines from the stream. As long as you have a valid line, you can compute its position on the page, then call the DrawString method on the Graphics object you get from the PrintPageEventArgs parameter, e.

This method is overloaded. The version you'll use takes six parameters, as shown in Example 3-20.

Example 3-20. Calling the DrawString method
 yPosition = top + ctr * _     printFont.GetHeight(e.Graphics) printPageEventArgs.Graphics.DrawString( _ line, _ printFont, _ Brushes.Black, _ left, _ yPosition, _ New StringFormat(  )) 

In Example 3-20:


line

Is the string to draw on the page


printFont

Is the font to use to print the text


Brushes.Black

Is a standard enumeration for the black color to draw the text


left

Is the x coordinate at which to begin drawing


yPosition

Is the y coordinate at which to begin drawing


StringFormat

Is an object that specifies the formatting attributes, such as line spacing and alignment; here, you are using the default provided by the StringFormat class



Programming Visual Basic 2005
Programming Visual Basic 2005
ISBN: 0596009496
EAN: 2147483647
Year: 2006
Pages: 162
Authors: Jesse Liberty

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net