Share via


如何打印窗体(Windows 窗体 .NET)

在开发过程中,通常需要打印 Windows 窗体的副本。 下面的代码示例演示如何使用 CopyFromScreen 方法打印当前窗体的副本。

在以下示例中,一个名为“Button1”的按钮被添加到窗体中。 单击“Button1”按钮时,它会将窗体保存到内存中的图像,然后将其发送给打印对象。

示例

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

可靠编程

以下情况可能会导致异常:

  • 你没有访问打印机的权限。

  • 未安装打印机。

.NET 安全性

若要运行此代码示例,必须有权访问与计算机一起使用的打印机。

另请参阅