How to Print Windows Form in C#

By FoxLearn 8/25/2024 3:03:55 AM   10.68K
To print a Windows Form in C#, you'll need to use the PrintDocument class along with the PrintPreviewDialog and PrintDialog to set up and manage the printing process.

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.

print windows forms in c#

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.

c# ef model

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:

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