Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
In the course of designing an app, you might design a form in such a way that it represents a printed page. The following code example shows how to print a copy of the current form by using the CopyFromScreen method.
Example
To run the example code, add two components to a form with the following settings:
Object | Property\Event | Value |
---|---|---|
Button | Name |
Button1 |
Click |
Button1_Click |
|
PrintDocument | Name |
PrintDocument1 |
PrintPage |
PrintDocument1_PrintPage |
The following code is run when the Button1
is clicked. The code creates a Graphics
object from the form and saves its contents to a Bitmap
variable named memoryImage
. The PrintDocument.Print method is called, which invokes the PrintPage event. The print event handler draws the memoryImage
bitmap on the printer page's Graphics
object. When the print event handler code returns, the page is printed.
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 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
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
End Class
Robust programming
The following conditions 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
.NET Desktop feedback