Q. I was wondering how to print a form in VB.NET. With VB6 you could use 'PrintForm', but this is not supported by VB.NET. No books I have read have discussed this either. I just want to print the form as is on the screen by clicking a click button on the form. Something so simple has really got me stumped and frustrated. Can you help me out with this?

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, ...);

  }

}

 

Of course, this is just the tip of what the printing architecture in WinForms allows. I recommend the documentation and my upcoming WinForms books for more information.

Feedback

I have feedback on this Ask The Wonk answer