Else strFormat.Alignment = StringAlignment.Center e.Graphics.DrawString(''Print Mode", tFont, tBrush, _ New RectangleF(e.PageBounds.X, 50, _ e.PageBounds.Width, 100), strFormat) End If
The last three statements in the PrintPage event handler print three rectangles: a red rectangle that delimits the printout's margins, a yellow rectangle around the page (from the page's upper-left corner to the page's lower-right corner), and a gray rectangle around the page's printable area, which is the entire page minus the printer margins, given by the RenderingOrigin property. The yellow rectangle doesn't take into consideration the areas of the page that can't be printed and will not be visible in the preview pane (it will be drawn at the very edge of the page). If you print the page on a color printer, you'll see that the yellow rectangle doesn't start at the upper-left corner of the page and is slightly smaller than the page. The three rectangles are printed with the following statements:
e.Graphics.DrawRectangle(New Pen(Color.Red, 3), _ New Rectangle(e.MarginBounds.X, e.MarginBounds.Y, _ e.MarginBounds.Width, e.MarginBounds.Height)) e.Graphics.DrawRectangle(New Pen(Color.Yellow, 3), _ New Rectangle(0, 0, e.PageBounds.Width, _ e.PageBounds.Height)) e.Graphics.DrawRectangle(New Pen(Color.Gray, 3), _ New Rectangle(e.Graphics.RenderingOrigin.X, _ e.Graphics.RenderingOrigin.Y, _ e.PageSettings.PaperSize.Width - e.Graphics.RenderingOrigin.X, _ e.PageSettings.PaperSize.Height - e.Graphics.RenderingOrigin.Y))
The X and Y properties of the RenderingOrigin object are the sizes of the two non-printable bands at the upper-left corner of the page. There are two equivalent bands at the page's lower-right corner as well.
You've seen examples of printing simple graphics elements, such as text and rectangles, how to take into consideration the page's geometry, and how to control the appearance of the graphics elements on the page, especially the appearance of text. It's time to look at a few more practical and interesting examples.
Our first real-world example is a Print method for the TextBox control. We're actually wondering, What good is a TextBox control without a method to print its contents? A procedure that prints a text segment should be fairly simple, but it's not. As you will see, there are various parameters you must take into consideration, and a robust text-printing mechanism is a must-have tool for a developer. Most professional developers will purchase a third-party tool that can generate elaborate printouts, but you may find a few good uses for a simple text-printing tool.
The TextBox control uses a single font for its text, which simplifies our code immensely. To demonstrate how to print text with the Framework's printing controls, we'll create an enhanced TextBox control with a Print and a Preview method. If you were asked to suggest an enhancement to the TextBox