C# 打印前显示打印对话框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15985909/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 18:40:45  来源:igfitidea点击:

Show Print Dialog before printing

c#printdialog

提问by user2257581

I want to show the print dialog box before printing the document, so the user can choose another printer before printing. The code for printing is:

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

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

will this code be able to print the current form?

这段代码能打印当前的表格吗?

采纳答案by KF2

You have to use PrintDialog

你必须使用 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");
 }

Edited(from Comment)

已编辑(来自评论)

On 64-bitWindows and with some versions of .NET you may have to set pdi.UseExDialog = true; for the dialog window to appear.

64-bitWindows 和某些版本的 .NET 上,您可能需要设置pdi.UseExDialog = true; 出现对话框窗口。

回答by chintu

For the sake of completeness, the code should include a using directive

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

using System.Drawing.Printing;

for further reference please goto PrintDocument Class

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