Question

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?

Was it helpful?

Solution

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top