8

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

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);
        }

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

4

2 回答 2

18

你必须使用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-bitWindows 和某些版本的 .NET 上,您可能必须设置pdi.UseExDialog = true; 以显示对话窗口。

于 2013-04-13T08:47:51.810 回答
3

为了完整起见,代码应包含 using 指令

using System.Drawing.Printing;

如需进一步参考,请转到 PrintDocument 类

于 2015-04-17T14:25:38.030 回答