428 Part III Designing the User Interface
'Compute how many chars and lines can fit based on sizeMeasure
e.Graphics.MeasureString(StringToPrint, PrintFont, _
sizeMeasure, strFormat, numChars, numLines)
'Compute string that will fit on a page
stringForPage = StringToPrint.Substring(0, numChars)
'Print string on current page
e.Graphics.DrawString(stringForPage, PrintFont, _
Brushes.Black, rectDraw, strFormat)
'If there is more text, indicate there are more pages
If numChars < StringToPrint.Length Then
'Subtract text from string that has been printed
StringToPrint = StringToPrint.Substring(numChars)
e.HasMorePages = True
Else
e.HasMorePages = False
'All text has been printed, so restore string
StringToPrint = RichTextBox1.Text
End If
This event procedure handles the actual printing of the text document, and it does so
by carefully defining a printing area (or printing rectangle) based on the settings in the
Page Setup dialog box. Any text that fits within this area can be printed normally; text
that’s outside this area needs to be wrapped to the following lines, or pages, as you’d
expect to happen in a standard Windows application.
The printing area is defined by the rectDraw variable, which is based on the RectangleF
class. The strFormat variable and the Trimming method are used to trim strings that
extend beyond the edge of the right margin. The actual text strings are printed by
the DrawString method, which you’ve already used in this chapter. The HasMorePages
property is used to specify whether there are additional pages to be printed. If no
additional pages remain, the HasMorePage property is set to False, and the contents
of the StringToPrint variable are restored to the contents of the RichTextBox1 object.
- Click the Save All button on the toolbar to save your changes, and then specify the
C:\Vb10sbs\Chap17 folder as the location.
That’s a lot of typing! But now you’re ready to run the program and see how printing text
files on multiple pages works.
Run the Print File program
Tip The complete Print File program is located in the C:\Vb10sbs\Chap17\Print File folder.
- Click the Start Debugging button on the toolbar.
Your program runs in the IDE. Notice that the Print button is currently disabled because
you haven’t selected a file yet.
- Click the Open button.
The program displays an Open dialog box.