Unfortunately, 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, EventArgs e )
{
PrintDialog printDialog1 = new PrintDialog();
printDialog1.Document = printDocument1;
DialogResult result = printDialog1.ShowDialog();
if ( result == DialogResult.OK )
printDocument1.Print();
}
For detailed information about print framework, please see Windows Forms Print Support (Visual Studio) in the MSDN Library.
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.
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 );
}
The above referenced the article Screen Capturing a Form in .NET - Using GDI in GDI+" by Michael Gold on C# Corner.
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 any time.
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 );
Lion Shi, Microsoft