Export (0) Print
Expand All

Code: Printing the Form (Visual C#)

Visual Studio .NET 2003

This example demonstrates printing a copy of the current form.

Example

[System.Runtime.InteropServices.DllImport("gdi32.dll")]
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);
   mygraphics.ReleaseHdc(dc1);
   memoryGraphics.ReleaseHdc(dc2);
}
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)
{
   CaptureScreen();
   printDocument1.Print();
}

Compiling the Code

This example requires:

  • A PrintDocument component named printDocument1 with a PrintPage event handler.
  • A Button named printButton with a Click event handler.

The example code replaces the existing event handlers. The form is printed 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.

Security

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

Show:
© 2015 Microsoft