This documentation is archived and is not being maintained.

Code: Print Previewing the Form (Visual C#)

Visual Studio .NET 2003

This example demonstrates print previewing a copy of the current form.


public static extern long BitBlt (IntPtr hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, IntPtr hdcSrc, int nXSrc, int nYSrc, int dwRop);
private Bitmap memoryImage;
private void CaptureScreen()
   Graphics mygraphics = this.CreateGraphics();
   Size s = this.Size;
   memoryImage = new Bitmap(s.Width, s.Height, mygraphics);
   Graphics memoryGraphics = Graphics.FromImage(memoryImage);
   IntPtr dc1 = mygraphics.GetHdc();
   IntPtr dc2 = memoryGraphics.GetHdc();
   BitBlt(dc2, 0, 0, this.ClientRectangle.Width, this.ClientRectangle.Height, dc1, 0, 0, 13369376);
private void printDocument1_PrintPage(System.Object sender, System.Drawing.Printing.PrintPageEventArgs e)
   e.Graphics.DrawImage(memoryImage, 0, 0);
private void printButton_Click(System.Object sender, System.EventArgs e)

Compiling the Code

This example requires:

  • A PrintDocument component named printDocument1 with a PrintPage event handler.
  • A PrintPreviewDialog component named printPreviewDialog1 with its Document property set to printDocument1.
  • A Button named printButton with a Click event handler.

The example code replaces the existing event handlers. A print preview of the form is displayed when printButton is clicked.

Robust Programming

The following conditions may cause an exception:

  • You do not have permission to access the printer.
  • You do not have permission to use unmanaged code.
  • There is no printer installed.
  • The print preview dialog box was previously disposed. This occurs after the print preview dialog box is closed.


In order to run this example, you must have permission to execute unmanaged code and to access the printer.

See Also

Graphics Programming Example Topics | Printing with the PrintDocument Component | Rendering Images with GDI+ | Printing Graphics in Windows Forms | PrintDocument Class