Escape button to close Windows Forms form in C#

后端 未结 8 1219
心在旅途
心在旅途 2020-12-02 06:15

I have tried the following:

private void Form1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
    if ((Keys) e.KeyValue == Keys.Escape)
               


        
8条回答
  •  遥遥无期
    2020-12-02 06:47

    The accepted answer indeed is correct, and I've used that approach several times. Suddenly, it would not work anymore, so I found it strange. Mostly because my breakpoint would not be hit for ESC key, but it would hit for other keys.

    After debugging I found out that one of the controls from my form was overriding ProcessCmdKey method, with this code:

    protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
        // ...
        if (keyData == (Keys.Escape))
        {
            Close();
            return true;
        }
        return base.ProcessCmdKey(ref msg, keyData);
    }
    

    ... and this was preventing my form from getting the ESC key (notice the return true). So make sure that no child controls are taking over your input.

提交回复
热议问题