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;
}
}// 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);
}
}
}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.