سؤال

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?
هل كانت مفيدة؟

المحلول

You can check the result of the ShowDialog method:

if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
   //Print
}

نصائح أخرى

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

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...
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top