Escape button to close Windows Forms form in C#

后端 未结 8 1165
心在旅途
心在旅途 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 07:01

    You should just be able to set the Form's CancelButton property to your Cancel button and then you won't need any code.

    0 讨论(0)
  • 2020-12-02 07:02

    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);
    }
    
    0 讨论(0)
提交回复
热议问题