views:

216

answers:

2

I'm working on a WinForms application that uses System.Windows.Forms.PrintPreviewDialog to display a Print Preview dialog. When the user presses ESC in that dialog, I'd like to close the dialog. Unfortunately, I can't figure out how to do this. I've tried to install a KeyDown/PreviewKeyDown event handler, but it never gets called. I also tried setting focus to the dialog (and to its PrintPreviewControl), thinking that was the issue, but that didn't help either. Does anyone have any idea how to make this work?

A: 

I haven't tried this, but don't System.Windows.Formss call CancelButton when you press Esc? Try creating a dummy Cancel button which calls .Close on the form.

Dour High Arch
That's an interesting possibility, but I'd rather not have to add any additional controls to the form. I found a solution that involves overriding the dialog's `ProcessCmdKey` function (see my own answer, elsewhere on this page), which I'm satisfied with.
Emerick Rogul
+2  A: 

I ended up customizing PrintPreviewDialog and overriding its ProcessCmdKey method to close the form when the user presses ESC. This seems like the cleanest solution.

Here's the code that I wrote:

using System.Windows.Forms;

namespace MyProject.UI.Dialogs
{
  class CustomPrintPreviewDialog : PrintPreviewDialog
  {
    protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
      // Close the dialog when the user presses ESC
      if (keyData == Keys.Escape)
      {
        this.Close();
        return true;
      }

      return base.ProcessCmdKey(ref msg, keyData);
    }
  }
}
Emerick Rogul
Good solution, thanks for posting it to your question.
Dour High Arch
Thanks, it was really helpful
Noam Gal