In this article, we will discuss how to print an entire Windows Form using Print Dialog & Print Preview tools in a Windows Forms application, step-by-step. It displays the actual printing page size and print area and print page type (single, double) in the the entire designed form.
Print Preview tool
It is an open tool and supports all the Visual Studio versions. We use this tool to show the print preview of the page. The PrintPreviewDialog is convenient and easy to use. All you need to do is to create an instance of the dialog class and assign your Print Document object to the Document property.
Print Dialog tool
This tool helps to print the dialog control that is used to open the Windows Print Dialog and lets the user select the printer and set printer, and paper properties to print a file.
Let's begin.
Step 1. Click New >> Project >> Visual C# >> Windows >> Windows Forms Application. Enter your Project name and click OK.
Step 2. Click the View->Select Toolbox. We are using this Toolbox to design the Form in the Windows application and Add the Print (Button).
Step 3. In Toolbox, we have to add Print Dialog & Print Preview. Just Drag & Drop in the form.
Step 4. Double-click the Print Document properties and printDocument1_PrintPage to be completed for the event to make the function more accurate.
C# Code
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
e.Graphics.DrawImage(bitmap, 0, 0);
}
Step 5. Double-click the Print button and button2_Click to be completed for the event to make the function more accurate.
Header File
using System.Drawing.Printing;
C# Code
private void button2_Click(object sender, EventArgs e)
{
Panel panel = new Panel();
this.Controls.Add(panel);
Graphics grp = panel.CreateGraphics();
Size formSize = this.ClientSize;
bitmap = new Bitmap(formSize.Width, formSize.Height, grp);
grp = Graphics.FromImage(bitmap);
Point panelLocation = PointToScreen(panel.Location);
grp.CopyFromScreen(panelLocation.X, panelLocation.Y, 0, 0, formSize);
printPreviewDialog1.Document = printDocument1;
printPreviewDialog1.PrintPreviewControl.Zoom = 1;
printPreviewDialog1.ShowDialog();
}
Bitmap bitmap;
private void CaptureScreen()
{
Graphics myGraphics = this.CreateGraphics();
Size s = this.Size;
bitmap = new Bitmap(s.Width, s.Height, myGraphics);
Graphics memoryGraphics = Graphics.FromImage(bitmap);
memoryGraphics.CopyFromScreen(this.Location.X, this.Location.Y, 0, 0, s);
}
Step 6. At Runtime, the dialog will show generating previews like given below. It will show the time of printing also.
Step 7. Press F5 or ".Build and Run" the application.
Finally, we have successfully printed the entire Windows Forms application using the Print dialog and Print Preview.