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?

SetFreeByTruth
  • 819
  • 8
  • 23
user2257581
  • 87
  • 1
  • 1
  • 9

2 Answers2

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.

KF2
  • 9,887
  • 8
  • 44
  • 77
  • when press the button,print dialog does not open,but the messagebox displaying Print Cancelled is shown – user2257581 Apr 13 '13 at 08:51
  • @ user2257581:i test it now,it work,make a new application and test it again,see it work – KF2 Apr 13 '13 at 08:57
  • 2
    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 http://stackoverflow.com/q/6385844/202010 for details. – Thomas Gerstendörfer Apr 13 '13 at 09:00
  • @ThomasGerstendörfer where to write that code? before the `if` statement? – user2257581 Apr 13 '13 at 09:02
  • @user2257581 Yes, just above or below the `pdi.Document = pd;` line. – Thomas Gerstendörfer Apr 13 '13 at 09:03
  • 2
    Not sure why I am the only one experiencing this but pdi (PrintDialog) does not have a Document property for me... – Shumii Nov 14 '13 at 15:31
  • 2
    @Shumii 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`. – Grx70 Apr 03 '15 at 10:26
3

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

using System.Drawing.Printing;

for further reference please goto PrintDocument Class

chintu
  • 41
  • 1