Reputation: 389
Hello I am modifying a WinForms program. I would like to make it possible to exit any form pressing Esc key.
I tried to bind event to this method, and it works.
private void form_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Escape)
{
this.Dispose();
}
}
But I want to apply this event to a lot of forms in my project, what is a smart way to do it avoiding to paste this method and bind it to the event manually for each form?
Upvotes: 0
Views: 1205
Reputation: 15247
You can use a decorator pattern, such as :
class CustomForm : Form
{
public CustomForm()
{
// automatically bind a keypress event
this.KeyPress += new EventHandler(form_KeyPress);
}
private void form_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Escape)
{
this.Close(); // Close instead of disposing
}
}
}
And then, all the forms you'd like to have this behaviour can inherit from CustomForm
instead of Form
Upvotes: 2
Reputation:
You should override the ProcessCommandKey
method of the Form
base class like that by calling Close()
instead of Dispose()
because calling dispose is not a good practice:
public partial class EscapableForm
{
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
switch ( keyData )
{
case Keys.Escape:
Close();
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
}
Overriding the method is here better than using an event since it allows a better design consistency.
So anywhere the user is, no matter the active control, keys are catched and you can manage what you want. You can also add any UX condition like an AllowClose
conditional variable.
To not repeat the code you can create the custom form class file and replace the standard Form base class used by the Visual STudio Designer in any final form like suggested by @Cid.
Upvotes: 1