Show Print Dialog before printing

徘徊边缘 提交于 2019-11-27 03:31:17

问题


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?


回答1:


You have to use 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-bit Windows and with some versions of .NET you may have to set pdi.UseExDialog = true; for the dialog window to appear.




回答2:


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

using System.Drawing.Printing;

for further reference please goto PrintDocument Class



来源:https://stackoverflow.com/questions/15985909/show-print-dialog-before-printing

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!