Ask the Expert

How do I print a form in VB.NET?

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

This was first published in January 2003

There are Comments. Add yours.

 
TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Sort by: OldestNewest

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to: