How to make a form close when pressing the escape key?
You can set a property on the form to do this for you if you have a button on the form that closes the form already.
Set the CancelButton
property of the form to that button.
Gets or sets the button control that is clicked when the user presses the Esc key.
If you don't have a cancel button then you'll need to add a KeyDown
handler and check for the Esc key in that:
private void Form_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Escape)
{
this.Close();
}
}
You will also have to set the KeyPreview
property to true.
Gets or sets a value indicating whether the form will receive key events before the event is passed to the control that has focus.
However, as Gargo points out in his answer this will mean that pressing Esc to abort an edit on a control in the dialog will also have the effect of closing the dialog. To avoid that override the ProcessDialogKey
method as follows:
protected override bool ProcessDialogKey(Keys keyData)
{
if (Form.ModifierKeys == Keys.None && keyData == Keys.Escape)
{
this.Close();
return true;
}
return base.ProcessDialogKey(keyData);
}
Escape button to close Windows Forms form in C#
This will always work, regardless of proper event handler assignment, KeyPreview
, CancelButton
, etc:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
if (keyData == Keys.Escape) {
this.Close();
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
Escape key close panel c# winforms
Panel control cant be focused so you cant handle key down event.
Try to handle key down event of parent control or in more broad way override ProcessCmdKey
method:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
// your logic here. For example:
switch (keyData)
{
case Keys.Escape:
//do something
break;
}
return base.ProcessCmdKey(ref msg, keyData);
}
How to exit all forms with esc key?
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.
Escape key is closing a Windows Forms form with no code or settings tied to it
The first suspect is CancelButton
of the form. Also check the DialogResult
of the cancel button.
If you set the CancelButton
of the form to a button, pressing the Esc key calls the button's Click
event, sets the form's DialogResult
to Cancel
and closes the form. Also when you set the DialogResult
property of a button to anything other than None
, clicking the button will close the form. From MSDN:
If the DialogResult for this property is set to anything other than None, and if the parent form was displayed through the ShowDialog method, clicking the button closes the parent form without your having to hook up any events.
To investigate further, override OnFormClosing
method on the form, set a break-point on the method, and when the break-point is hit, give us the current call-stack (from the Call Stack window).
How do I close a form when the ESC key was hit, but only if no Control handled it?
You are competing Big Time over the Escape key. Along with the Enter key, that's a very important key in the standard Windows user interface. Just drop a button on form and set the form's CancelButton property to some other button, that will suck the keystroke to that button.
To compete with that, you have to create a control that tells Winforms that you really think that the Escape key is more important. That requires overriding the IsInputKey property. Like this:
using System;
using System.Windows.Forms;
class MyTexBox : TextBox {
protected override bool IsInputKey(Keys keyData) {
if (keyData == Keys.Escape) return true;
return base.IsInputKey(keyData);
}
protected override void OnKeyDown(KeyEventArgs e) {
if (e.KeyData == Keys.Escape) {
this.Text = ""; // for example
e.SuppressKeyPress = true;
return;
}
base.OnKeyDown(e);
}
}
How do you get the ESC key to close a dialog in Winforms?
Set the CancelButton
property of the form to reference your Cancel button.
C# Problems with getting the form to close with the Esc key is pressed
You have to first enable KeyPreview
of your windows form. Go to form property and set the KeyPreview
to true
. Your code should work then.
Assigning escape key to a button in windows form in C#
Set KeyPreview = true;
for the form and then override form's OnKeyDown
method something like this:
protected override void OnKeyDown(KeyEventArgs e)
{
base.OnKeyDown(e);
if (e.Modifiers == Keys.None && e.KeyCode == Keys.Escape)
//your button click event handler call here like button1_Click(null, null);
}
Related Topics
Replace Part of a JSON with Other (Using a String Token)
Receiving JSON Data Back from Http Request
Calling Async Methods from Non-Async Code
How to Generate a Unique Token Which Expires After 24 Hours
Add a Package with a Local Package File in 'Dotnet'
ASP.NET MVC - Passing Parameters to the Controller
How to Split an Ienumerable into Two by a Boolean Criteria Without Two Queries
Why Is There Huge Performance Hit in 2048X2048 Versus 2047X2047 Array Multiplication
Why Does Ienumerable<T> Inherit from Ienumerable
How to Implement Custom Authentication in ASP.NET MVC 5
Do I Need to Lock or Mark as Volatile When Accessing a Simple Boolean Flag in C#
Dependency Injection - New Instance Required in Several of a Classes Methods
Why How to Not Edit a Method That Contains an Anonymous Method in the Debugger
Convert an Object to an Xml String
System.Badimageformatexception: Could Not Load File or Assembly