Asked by adamperks81. Answered by the Wonk on January 6, 2003
A.
Unfortunately, dumping a Form directly to the printer is not supported in WinForms. However, the printing architecture in .NET is very simple and does allow you to print whatever you want using drawing commands from the System.Drawing namespace. The basic unit of printing in WinForms is the print document. A print document describes the characteristics of what’s to be printed, like the title of the document, and provides the events at various parts of the printing process, like that it’s time to print a page. The print document is modeled using the PrintDocument component from the System.Drawing.Printing namespace and is available from the Toolbox. The basic usage of a PrintDocument object is to create an instance, subscribe to at least the PrintPage event, call the Print method and handle the PrintPage event:
PrintDocument printDocument1;
void InitializeComponent() {
this.printDocument1 = new PrintDocument();
...
this.printDocument1.PrintPage +=
new PrintPageEventHandler(this.printDocument1_PrintPage);
...
}
void printButton_Click(object sender, System.EventArgs e) {
printDocument1.DocumentName = fileName;
printDocument1.Print();
}
void printDocument1_PrintPage(object sender, PrintPageEventArgs e) {
// Draw onto the e.Graphics object
Graphics g = e.Graphics;
using( Font font = new Font("Lucida Console", 72) ) {
g.DrawString("Hello,\nPrinter", font, ...);
}
}