How to print a Form (Windows Forms .NET)

As part of the development process, you typically will want to print a copy of your Windows Form. The following code example shows how to print a copy of the current form by using the CopyFromScreen method.

In the following example, a button named Button1 is added to the form. When the Button1 button is clicked, it saves the form to an image in memory, and then sends it to the print object.

Example

namespace Sample_print_win_form1
{
    public partial class Form1 : Form
    {
        Bitmap memoryImage;
        public Form1()
        {
            InitializeComponent();
        }

        private void Button1_Click(object sender, EventArgs e)
        {
            Graphics myGraphics = this.CreateGraphics();
            Size s = this.Size;
            memoryImage = new Bitmap(s.Width, s.Height, myGraphics);
            Graphics memoryGraphics = Graphics.FromImage(memoryImage);
            memoryGraphics.CopyFromScreen(this.Location.X, this.Location.Y, 0, 0, s);
            
            printDocument1.Print();
            
        }
        private void PrintDocument1_PrintPage(System.Object sender,
           System.Drawing.Printing.PrintPageEventArgs e) =>
               e.Graphics.DrawImage(memoryImage, 0, 0);
        
    }
}
Public Class Form1
    
    Dim memoryImage As Bitmap

    Private Sub printDocument1_PrintPage(ByVal sender As System.Object, 
       ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage

        e.Graphics.DrawImage(memoryImage, 0, 0)
        
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
         
        Dim myGraphics As Graphics = Me.CreateGraphics()
        Dim s As Size = Me.Size
        memoryImage = New Bitmap(s.Width, s.Height, myGraphics)
        Dim memoryGraphics As Graphics = Graphics.FromImage(memoryImage)
        memoryGraphics.CopyFromScreen(Me.Location.X, Me.Location.Y, 0, 0, s)
        
        PrintDocument1.Print()
        
    End Sub
End Class

Robust programming

The following conditions may cause an exception:

  • You don't have permission to access the printer.

  • There's no printer installed.

.NET security

To run this code example, you must have permission to access the printer you use with your computer.

See also