閱讀英文

共用方式為


如何:列印 Windows Form

在開發過程中,您通常會想要列印 Windows 表單的複本。 下列程式碼範例示範如何使用 CopyFromScreen 方法列印目前表單的複本。

範例

C#

using System;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Printing;

public class Form1 :
    Form
{
    private Button printButton = new Button();
    private PrintDocument printDocument1 = new PrintDocument();

    public Form1()
    {
        printButton.Text = "Print Form";
        printButton.Click += new EventHandler(printButton_Click);
        printDocument1.PrintPage += new PrintPageEventHandler(printDocument1_PrintPage);
        this.Controls.Add(printButton);
    }

    void printButton_Click(object sender, EventArgs e)
    {
        CaptureScreen();
        printDocument1.Print();
    }

    Bitmap memoryImage;

    private void CaptureScreen()
    {
        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);
    }

    private void printDocument1_PrintPage(System.Object sender,
           System.Drawing.Printing.PrintPageEventArgs e)
    {
        e.Graphics.DrawImage(memoryImage, 0, 0);
    }

    public static void Main()
    {
        Application.Run(new Form1());
    }
}

穩固程式設計

以下條件可能會造成例外狀況:

  • 您沒有存取印表機的權限。

  • 未安裝印表機。

.NET Framework 安全性

為了執行此程式碼範例,您必須具有存取與電腦搭配使用之印表機的權限。

另請參閱