How to make a form close when pressing the escape key?

后端 未结 5 1607
离开以前
离开以前 2021-01-30 19:31

I have a small form, which comes up when I press a button in a Windows Forms application.

I want to be able to close the form by pressing the escape key. How could I do t

5条回答
  •  难免孤独
    2021-01-30 20:08

    The best way i found is to override the "ProcessDialogKey" function. This way canceling a open control is still possible because the function is only called when no other control uses the pressed Key.

    This is the same behaviour as when setting a CancelButton. Using the KeyDown Event fires always and thus the form would close even when it should cancel the edit of an open editor.

    protected override bool ProcessDialogKey(Keys keyData)
    {
        if (Form.ModifierKeys == Keys.None && keyData == Keys.Escape)
        {
            this.Close();
            return true;
        }
        return base.ProcessDialogKey(keyData);
    }
    

提交回复
热议问题