1

If I run this code, and press cancel on the PrintDialog, it still prints. How can I tell if the use pressed cancel?

PrintDocument document = new PrintDocument();
PrintDialog dialog = new PrintDialog();

dialog.ShowDialog();
document.PrinterSettings = p.PrinterSettings;
document.Print();

Addendum

WebBrowser w = new WebBrowser();
w.ShowPrintDialog(); //.ShowPrintDialog returns a void, how can I deal with this?
sooprise
  • 22,657
  • 67
  • 188
  • 276

3 Answers3

7

You can check the result of the ShowDialog method:

if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
   //Print
}
SwDevMan81
  • 48,814
  • 22
  • 151
  • 184
John Koerner
  • 37,428
  • 8
  • 84
  • 134
3

ShowDialog returns a dialog result enumeration. It will either be OK, or Cancel.

PrintDocument document = new PrintDocument();
PrintDialog dialog = new PrintDialog();

if(dialog.ShowDialog() == DialogResult.Ok)
{
    document.PrinterSettings = p.PrinterSettings;
    document.Print();
}
Craigt
  • 3,418
  • 6
  • 40
  • 56
  • 1
    Is there anything I can do with WebBrowser.ShowPrintDialog?It returns a void and not a DialogResult. – sooprise Feb 15 '11 at 19:25
  • Unfortunately I don't thing there is a way to handle this. What would you like to do with the result? i.e. if the dialog was cancelled, what code would execute? – Craigt Feb 16 '11 at 05:49
0

The answers above are correct for System.Windows.Forms.PrintDialog. However, if you're not building a Forms application, the PrintDialog you will use is System.Windows.Controls.PrintDialog. Here, ShowDialog returns a bool?:

var dialog = new System.Windows.Controls.PrintDialog();

if (dialog.ShowDialog() == true)
{
    // Print...
}
Knelis
  • 6,782
  • 2
  • 34
  • 54