如何在 Windows 窗体中选择附加到用户计算机的打印机

通常,用户希望选择要打印到的默认打印机以外的打印机。 用户可以使用 PrintDialog 组件从当前安装的打印机中选择打印机。 通过 PrintDialog 组件捕获 PrintDialog 组件的 DialogResult,并用于选择打印机。

在以下过程中,选择要打印到默认打印机的文本文件。 然后接着实例化 PrintDialog 类。

选择打印机,然后打印文件

  1. 选择要使用 PrintDialog 组件的打印机。

    在以下代码示例中,有两个正在处理的事件。 在Button 控件的 Click 事件中,首先实例化 PrintDialog 类,同时在 DialogResult 属性中捕获用户选择的打印机。

    第二个事件是 PrintDocument 组件的 PrintPage 事件,示例文档将打印到指定的打印机。

    Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click  
       Dim PrintDialog1 As New PrintDialog()  
       PrintDialog1.Document = PrintDocument1  
       Dim result As DialogResult = PrintDialog1.ShowDialog()  
    
       If (result = DialogResult.OK) Then  
         PrintDocument1.Print()  
       End If
    
    End Sub  
    
    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 button1_Click(object sender, System.EventArgs e)  
    {  
       PrintDialog printDialog1 = new PrintDialog();  
       printDialog1.Document = printDocument1;  
       DialogResult result = printDialog1.ShowDialog();  
       if (result == DialogResult.OK)  
       {  
          printDocument1.Print();  
       }  
    }  
    
    private void printDocument1_PrintPage(object sender,
    System.Drawing.Printing.PrintPageEventArgs e)  
    {  
       e.Graphics.FillRectangle(Brushes.Red,
         new Rectangle(500, 500, 500, 500));  
    }  
    
    private:  
       void button1_Click(System::Object ^ sender,  
          System::EventArgs ^ e)  
       {  
          PrintDialog ^ printDialog1 = gcnew PrintDialog();  
          printDialog1->Document = printDocument1;  
          System::Windows::Forms::DialogResult result =
             printDialog1->ShowDialog();  
          if (result == DialogResult::OK)  
          {  
             printDocument1->Print();  
          }  
       }  
    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);  
    this.button1.Click += new System.EventHandler(this.button1_Click);  
    
    this->printDocument1->PrintPage += gcnew  
       System::Drawing::Printing::PrintPageEventHandler  
       (this, &Form1::printDocument1_PrintPage);  
    this->button1->Click += gcnew  
       System::EventHandler(this, &Form1::button1_Click);  
    

另请参阅