Close Application at Press of Escape Button






4.88/5 (17 votes)
How to close Form at pressing of Escape Button.
There are various ways to close an application by pressing the Escape button, using C#. Here are a few:
- Way 1: Simply add the below given code in your Windows program:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == Keys.Escape) this.Close();
bool res = base.ProcessCmdKey(ref msg, keyData);
return res;
}
KeyPress
event of a form:if (e.KeyChar == (char)27)
this.Close();
KeyPreview
' and change it from 'false
' to 'true
'. [By default, its value is false
.] Then write the below code in the KeyUp
event of the Form:private void Form1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Escape)
this.Close();
}