How to Print Windows Form in C#
By Tan Lee Published on Jul 02, 2017 11.47K
How to Print Windows Form in C#
Click New Project, then select Visual C# on the left, then Windows and then select Windows Forms Application. Name your project "PrintWindowsForms" and then click OK
Drag and drop Label, Button, DataGridView, TextBox control from the Visual Studio toolbox onto your form designer, then you can layout your form as shown below.
We use the Northwind database to play demo. If you haven't got Northwind database, you can view How to download and restore Northwind database in SQL Server
Create an EF Model as shown below.
We will retrieve data from the Northwind database, then display data to DataGridView.
Open your form in the Designer view, then drag a PrintDocument
component from the Toolbox onto your form.
This will add a PrintDocument
component to your form’s components tray.
Drag a PrintPreviewDialog
and a PrintDialog
component from the Toolbox onto your form.
Double-click the buttons to generate Click
event handlers and write the code to manage the print preview and printing process.
Here is an example of how to implement these handlers:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
private void printDocument1_PrintPage( object sender, System.Drawing.Printing.PrintPageEventArgs e) { //Draw form e.Graphics.DrawImage(bmp, 0, 0); } Bitmap bmp; private void btnPrint_Click( object sender, EventArgs e) { //Open print preview dialog Graphics g = this .CreateGraphics(); bmp = new Bitmap( this .Size.Width, this .Size.Height, g); Graphics mg = Graphics.FromImage(bmp); mg.CopyFromScreen( this .Location.X, this .Location.Y, 0, 0, this .Size); printPreviewDialog1.ShowDialog(); } private void Form1_Load( object sender, EventArgs e) { //Get product data using (NorthWindEntities db = new NorthWindEntities()) { productBindingSource.DataSource = db.Products.ToList(); } } |
printDocument1_PrintPage is where you define what gets printed. In this example, the form itself is captured as an image and printed.
Run your application, click the "Print" button to start the actual printing process.
VIDEO TUTORIAL
- How to Open and Show a PDF file in C#
- How to Get all Forms and Open Form with Form Name in C#
- How to zoom an image in C#
- How to Print a Picture Box in C#
- How to update UI from another thread in C#
- How to Search DataGridView by using TextBox in C#
- How to read and write to text file in C#
- How to save files using SaveFileDialog in C#