在 Windows 窗体中打印的基础是 PrintDocument 组件,更具体地说是 PrintPage 事件。 通过编写代码来处理 PrintPage 事件,可以指定要打印的内容以及如何打印它。
将 PrintDocument 组件添加到窗体。
编写代码来处理 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(System::Object ^ sender, System::Drawing::Printing::PrintPageEventArgs ^ e) { e->Graphics->FillRectangle(Brushes::Red, Rectangle(500, 500, 500, 500)); }
(Visual C# 和 Visual C++)将以下代码置于表单的构造函数中以注册事件处理程序。
this.printDocument1.PrintPage += new System.Drawing.Printing.PrintPageEventHandler (this.printDocument1_PrintPage);
printDocument1->PrintPage += gcnew System::Drawing::Printing::PrintPageEventHandler (this, &Form1::printDocument1_PrintPage);
你可能还希望为 BeginPrint 和 EndPrint 事件编写代码,这可能包括一个整数,表示需要打印的总页数,并且在每页打印后递减。
备注
可以将 PrintDialog 组件添加到您的表单中,为用户提供简洁高效的用户界面(UI)。 设置 PrintDialog 组件的 Document 属性,使您能够设置与您在窗体上处理的打印文档相关的属性。 有关 PrintDialog 组件的详细信息,请参阅 PrintDialog 组件。
有关 Windows 窗体打印作业的详细信息,包括如何以编程方式创建打印作业,请参阅 PrintPageEventArgs。