Unfortunately, there is no easy way to print a form. You may implement this function with the steps given 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 toolbox to your form. After that, you should create a PrintDialog and add the code to print the document.
[C#]
private void buttonPrint_Click(object sender, EventArgs e)
{
PrintDialog printDialog1 = new PrintDialog();
printDialog1.Document = printDocument1;
DialogResult result = printDialog1.ShowDialog();
if (result == DialogResult.OK)
printDocument1.Print();
}
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.
[C#]
using System.Drawing.Printing;
private void printDocument1_PrintPage( object sender, PrintPageEventArgs e)
{
Graphics graphic = CreateGraphics();
Image memImage = new Bitmap( Size.Width, Size.Height, graphic );
Graphics memGraphic = Graphics.FromImage( memImage );
IntPtr dc1 = graphic.GetHdc();
IntPtr dc2 = memGraphic.GetHdc();
BitBlt( dc2, 0, 0, ClientRectangle.Width,
ClientRectangle.Height, dc1, 0, 0, 13369376 );
graphic.ReleaseHdc( dc1 );
memGraphic.ReleaseHdc( dc2 );
e.Graphics.DrawImage( memImage, 0, 0 );
}
3. Declare the API function.
Please note the BitBlt function used in Step 2. It is an unmanaged function. You should use ‘DllImport’ attribute to import it to your code. Although, this is the Step 3, you may perform this step anytime.
[C#]
using System.Runtime.InteropServices;
[ DllImport( 'gdi32.dll' ) ]
private static extern bool BitBlt( IntPtr hdcDest,
int nXDestint nYDest, int nWidthint nHeight,
IntPtr hdcSrcint nXSrcint nYSrc, System.Int32 dwRop );
Share with