在设计应用的过程中,你可以以类似打印页面的形式设计窗体。 下面的代码示例演示如何通过使用 CopyFromScreen 方法来打印当前表单的副本。
示例:
若要运行示例代码,请将两个组件添加到具有以下设置的窗体:
物体 | 属性\事件 | 价值 |
---|---|---|
按钮 | Name |
Button1 |
Click |
Button1_Click |
|
PrintDocument | Name |
PrintDocument1 |
PrintPage |
PrintDocument1_PrintPage |
单击Button1
后,将运行以下代码。 该代码从窗体创建一个Graphics
对象,并将其内容保存到名为memoryImage
的Bitmap
变量中。 调用PrintDocument.Print方法,会触发PrintPage事件。 打印事件处理程序在打印机页Graphics
的对象上绘制memoryImage
位图。 当打印事件处理程序代码返回时,将打印页面。
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
可靠编程
以下条件会导致异常:
- 您无权访问打印机。
- 未安装打印机。
.NET 安全性
若要运行此代码示例,必须有权访问与计算机一起使用的打印机。