Live Chat Icon For mobile
Live Chat Icon

WinForms FAQ - Printing

Find answers for the most frequently asked questions
Expand All Collapse All

I am afraid there is not a very easy way to print a form. You may implement
this function with the steps below:

1.	Add a print function to your application.

To do this, you should add a PrintDocument component to your application. 
Please drag a PrintDocument from the tool box to your form. After that, you 
should create a PrintDialog and add the code to print the document.

		private void buttonPrint_Click(object sender, System.EventArgs e)
			PrintDialog printDialog1 = new PrintDialog();
			printDialog1.Document = printDocument1;
			DialogResult result = printDialog1.ShowDialog();
			if (result == DialogResult.OK)

For detailed information about print framework, please see 'Windows Forms 
Print Support' in the MSDN (October 2001).

2.	Draw the form when printing.

This step is a little complex. You should handle the PrintPage of the 
printDocument1 and draw the form to the printer device. In the event you 
may copy the form to an image and then draw it to the printer device. 

		private void printDocument1_PrintPage(object sender, 
System.Drawing.Printing.PrintPageEventArgs e)
			Graphics graphic = this.CreateGraphics();
			Size s = this.Size;
			Image memImage = new Bitmap(s.Width, s.Height, graphic);
			Graphics memGraphic = Graphics.FromImage(memImage);
			IntPtr dc1 = graphic.GetHdc();
			IntPtr dc2 = memGraphic.GetHdc();
			BitBlt(dc2, 0, 0, this.ClientRectangle.Width, 
this.ClientRectangle.Height, dc1, 0, 0, 13369376);

The above referenced the article 'Screen Capturing a Form in .NET - Using 
GDI in GDI+' by Michael Gold. You may find it at:

3.	Declare the API function.

Please note the BitBlt function used in Step 2. It is an unmanaged 
function. You should use DllImportAttribute attribute to import it to your 
code. Although, this is the Step 3, you may perform this step any time.

		private static extern bool BitBlt(
			IntPtr hdcDest, // handle to destination DC
			int nXDest, // x-coord of destination upper-left corner
			int nYDest, // y-coord of destination upper-left corner
			int nWidth, // width of destination rectangle
			int nHeight, // height of destination rectangle
			IntPtr hdcSrc, // handle to source DC
			int nXSrc, // x-coordinate of source upper-left corner
			int nYSrc, // y-coordinate of source upper-left corner
			System.Int32 dwRop // raster operation code

For more information about DllImportAttribute attribute please see:

(from Lion Shi ( on microsoft.public.dotnet.framework.windowsforms)


Share with

Couldn't find the FAQs you're looking for?

Please submit your question and answer.