I have tried the following:
private void Form1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
if ((Keys) e.KeyValue == Keys.Escape)
You should just be able to set the Form's CancelButton
property to your Cancel button and then you won't need any code.
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);
}