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?
views:
216answers:
2
A:
I haven't tried this, but don't System.Windows.Forms
s call CancelButton
when you press Esc? Try creating a dummy Cancel button which calls .Close
on the form.
Dour High Arch
2010-02-03 18:40:50
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
2010-02-05 14:44:01
+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
2010-02-05 14:41:48