如何在 Windows 窗体应用程序中显示打印预览

可以使用 PrintPreviewDialog 控件让用户通常在打印文档之前显示该文档。

为此,需要指定 PrintDocument 类的实例;这是要打印的文档。 有关将打印预览与 PrintDocument 组件配合使用的详细信息,请参阅 如何:使用打印预览在 Windows 窗体中打印

注释

若要在运行时使用 PrintPreviewDialog 控件,用户必须在其计算机上本地或通过网络安装打印机,因为这部分决定了 PrintPreviewDialog 组件如何确定打印时文档的外观。

PrintPreviewDialog 控件使用 PrinterSettings 类。 此外,PrintPreviewDialog 控件使用 PageSettings 类,就像 PrintPreviewDialog 组件一样。 PrintPreviewDialog 控件的 Document 属性中指定的打印文档是指 PrinterSettingsPageSettings 类的实例,这些实例用于在预览窗口中呈现文档。

使用 PrintPreviewDialog 控件查看页面

  • 使用 ShowDialog 方法可显示对话框,从而指定要使用的 PrintDocument

    在以下代码示例中,Button 控件的 Click 事件处理程序将打开 PrintPreviewDialog 控件的实例。 打印文档是在 Document 属性中指定的。 在下面的示例中,未指定打印文档。

    此示例要求你的窗体具有一个 Button 控件、一个名为 PrintDocumentmyDocument 组件和一个 PrintPreviewDialog 控件。

    Private Sub Button1_Click(ByVal sender As System.Object, _
       ByVal e As System.EventArgs) Handles Button1.Click
       ' The print document 'myDocument' used below
       ' is merely for an example.
       ' You will have to specify your own print document.
       PrintPreviewDialog1.Document = myDocument
       PrintPreviewDialog1.ShowDialog()
    End Sub
    
    private void button1_Click(object sender, System.EventArgs e)
    {
       // The print document 'myDocument' used below
       // is merely for an example.
       // You will have to specify your own print document.
       printPreviewDialog1.Document = myDocument;
       printPreviewDialog1.ShowDialog();
    }
    
    private:
       void button1_Click(System::Object ^ sender,
          System::EventArgs ^ e)
       {
          // The print document 'myDocument' used below
          // is merely for an example.
          // You will have to specify your own print document.
          printPreviewDialog1->Document = myDocument;
          printPreviewDialog1->ShowDialog();
       }
    

    (Visual C#、Visual C++)将以下代码置于表单的构造函数中以注册事件处理程序。

    this.button1.Click += new System.EventHandler(this.button1_Click);
    
    this->button1->Click += gcnew
       System::EventHandler(this, &Form1::button1_Click);
    

另请参阅