Share via


HOW TO:建立標準的 Windows Form 列印工作

更新:2007 年 11 月

Windows Form 中的列印基礎是 PrintDocument 元件,特別是 PrintPage 事件。藉由撰寫處理 PrintPage 事件的程式碼,您可指定列印項目和如何列印。

若要建立列印工作

  1. PrintDocument 元件加入至表單。

  2. 撰寫用來處理 PrintPage 事件的程式碼。

    您必須編寫自己的列印邏輯。此外,您必須指定所要列印的材料。

    在下列程式碼範例中,會在 PrintPage 事件處理常式中建立一個紅色矩形的樣本圖形,以做為要列印的材料。

    Private Sub PrintDocument1_PrintPage(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
       e.Graphics.FillRectangle(Brushes.Red, New Rectangle(500, 500, 500, 500))
    End Sub
    
    private void printDocument1_PrintPage(object sender, 
    System.Drawing.Printing.PrintPageEventArgs e)
    {
       e.Graphics.FillRectangle(Brushes.Red, 
         new Rectangle(500, 500, 500, 500));
    }
    
    private void printDocument1_PrintPage(Object sender,
    System.Drawing.Printing.PrintPageEventArgs e)
    {
       e.get_Graphics().FillRectangle(Brushes.get_Red(),
          new Rectangle(500, 500, 500, 500));
    }
    
    private:
       void printDocument1_PrintPage(System::Object ^ sender,
          System::Drawing::Printing::PrintPageEventArgs ^ e)
       {
          e->Graphics->FillRectangle(Brushes::Red,
             Rectangle(500, 500, 500, 500));
       }
    

    (Visual C#、Visual J# 和 Visual C++) 將下列程式碼放在表單的建構函式,以註冊事件處理常式。

    this.printDocument1.PrintPage += new
       System.Drawing.Printing.PrintPageEventHandler
       (this.printDocument1_PrintPage);
    
    this.printDocument1.add_PrintPage(new
       System.Drawing.Printing.PrintPageEventHandler
       (this.printDocument1_PrintPage));
    
    printDocument1->PrintPage += gcnew
       System::Drawing::Printing::PrintPageEventHandler
       (this, &Form1::printDocument1_PrintPage);
    

    您可能還需要撰寫 BeginPrintEndPrint 事件的程式碼,或許還包括代表總列印頁數的整數 (會在每一頁列印時遞減)。

    注意事項:

    您可以將 PrintDialog 元件加入至表單,為使用者提供清楚且高效率的使用者介面 (UI)。藉由設定 PrintDialog 元件的 Document 屬性,可讓您設定與表單上正在使用的列印文件有關的屬性。如需 PrintDialog 元件的詳細資訊,請參閱 PrintDialog 元件 (Windows Form)

    如需 Windows Form 列印工作細節 (包括如何以程式設計的方式來建立列印工作) 的詳細資訊,請參閱 PrintPageEventArgs

請參閱

參考

PrintDocument

其他資源

Windows Form 列印支援