2013-04-13 85 views
7

我想在打印文档前显示打印对话框,因此用户可以在打印前选择另一台打印机。打印的代码是:打印前显示打印对话框

private void button1_Click(object sender, EventArgs e) 
     { 
      try 
      { 
       PrintDocument pd = new PrintDocument(); 
       pd.PrintPage += new PrintPageEventHandler(PrintImage); 
       pd.Print(); 
      } 
      catch (Exception ex) 
      { 
       MessageBox.Show(ex.Message, ToString()); 
      } 
     } 
     void PrintImage(object o, PrintPageEventArgs e) 
     { 
      int x = SystemInformation.WorkingArea.X; 
      int y = SystemInformation.WorkingArea.Y; 
      int width = this.Width; 
      int height = this.Height; 

      Rectangle bounds = new Rectangle(x, y, width, height); 

      Bitmap img = new Bitmap(width, height); 

      this.DrawToBitmap(img, bounds); 
      Point p = new Point(100, 100); 
      e.Graphics.DrawImage(img, p); 
     } 

此代码是否能够打印当前表单?

回答

15

你必须使用PrintDialog

PrintDocument pd = new PrintDocument(); 
pd.PrintPage += new PrintPageEventHandler(PrintPage); 
PrintDialog pdi = new PrintDialog(); 
pdi.Document = pd; 
if (pdi.ShowDialog() == DialogResult.OK) 
{ 
    pd.Print(); 
} 
else 
{ 
     MessageBox.Show("Print Cancelled"); 
} 

编辑(从评论)

64-bit Windows和使用.NET的一些版本中,你可能必须设置pdi.UseExDialog = true;用于显示对话窗口。

+0

时按下按钮,打印对话框不开,但在MessageBox显示打印取消显示 – user2257581

+0

@ user2257581:我现在测试它,它工作,创建一个新的应用程序,并再次测试,看到它的工作 – KF2

+2

在64位Windows和一些版本的.NET,你可能必须设置'pdi.UseExDialog = true;'出现对话窗口。有关详细信息,请参阅http://stackoverflow.com/q/6385844/202010。 –

1

为了完整起见,密码应该包括使用指令

using System.Drawing.Printing; 

作进一步参考,请转到 PrintDocument Class

相关问题