Windows Forms 2.0 Programming (Microsoft .NET Development Series)
The basic unit of printing in Windows Forms is the print document. A print document describes the characteristics of what's to be printed, such as the document title, and provides events at various parts of the printing process, such as when it's time to print a page. .NET models the print document using the PrintDocument component (available from the VS05 Toolbox via the Windows Forms tab): namespace System.Drawing.Printing { class PrintDocument : Component { // Constructor public PrintDocument(); // Properties public PageSettings DefaultPageSettings { get; set; } public string DocumentName { get; set; } public bool OriginAtMargins { get; set; } public PrintController PrintController { get; set; } public PrinterSettings PrinterSettings { get; set; } // Methods public void Print(); // Events public event PrintEventHandler BeginPrint; public event PrintEventHandler EndPrint; public event PrintPageEventHandler PrintPage; public event QueryPageSettingsEventHandler QueryPageSettings; } }
To use a PrintDocument component, you create an instance, subscribe to at least the PrintPage event, call the Print method, and handle the PrintPage event: // MainForm.Designer.cs partial class MainForm { ... PrintDocument printDocument; ... void InitializeComponent() { ... this.printDocument = new PrintDocument(); ... this.printDocument.PrintPage += this.printDocument_PrintPage; ... } } // MainForm.cs using System.Drawing.Printing; ... partial class MainForm : Form { string fileName = "myFile.txt"; void printButton_Click(object sender, EventArgs e) { this.printDocument.DocumentName = this.fileName; this.printDocument.Print(); } void printDocument_PrintPage(object sender, PrintPageEventArgs e) { // Draw to the e.Graphics object that wraps the print target Graphics g = e.Graphics; using( Font font = new Font("Lucida Console", 72) ) { g.DrawString("Hello,\nPrinter", font, Brushes.Black, 0, 0); } } } The PrintPage event is triggered by a call to the PrintDocument object's Print method. The PrintPage event is responsible for actually rendering the state of the document to the printer surface using the Graphics object. The actual drawing is just like drawing on any other Graphics object, as discussed in Chapter 5: Drawing Basics, Chapter 6: Drawing Text, and Chapter 7: Advanced Drawing. Notice that this sample sets the DocumentName property of the document. This string shows up in the queue for the printer so that the user can manage the document being printed. |
Категории