Show Print Dialog before printing
Asked Answered
Y

2

8

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?

Yecies answered 13/4, 2013 at 8:39 Comment(0)
D
18

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.

Deandreadeane answered 13/4, 2013 at 8:47 Comment(7)
when press the button,print dialog does not open,but the messagebox displaying Print Cancelled is shownYecies
@ user2257581:i test it now,it work,make a new application and test it again,see it workDeandreadeane
On 64-bit Windows and with some versions of .NET you may have to set pdi.UseExDialog = true; for the dialog window to appear. See https://mcmap.net/q/976568/-printdialog-showdialog-not-showing-the-print-dialog-in-windows-7-with-64-bit/202010 for details.Mogerly
@ThomasGerstendörfer where to write that code? before the if statement?Yecies
@Yecies Yes, just above or below the pdi.Document = pd; line.Mogerly
Not sure why I am the only one experiencing this but pdi (PrintDialog) does not have a Document property for me...Arelus
@Arelus That's probably because you're using System.Windows.Controls.PrintDialog from PresentationFramework.dll whereas the answer refers to System.Windows.Forms.PrintDialog from System.Windows.Forms.dll.Monroe
M
3

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

using System.Drawing.Printing;

for further reference please goto PrintDocument Class

Marquand answered 17/4, 2015 at 14:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.