如何按ESC键使时一种形式结束? [英] How to make a form close when pressing the escape key?

查看:178
本文介绍了如何按ESC键使时一种形式结束?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小的形式,当我在一个 Windows窗体应用程序按下一个按钮,来了。

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

我希望能够通过按下Esc键关闭窗体。我怎么能这样做呢?我不知道事件的使用(form_closing?)?

I want to be able to close the form by pressing the escape key. How could I do this? I am not sure of the event to use (form_closing?)?

推荐答案

您可以在表格上设置一个属性来做到这一点你,如果你有一个已经关闭的窗体的窗体上的按钮。

You can set a property on the form to do this for you if you have a button on the form that closes the form already.

设置的 CancelButton 形式给该按钮的属性。

Set the CancelButton property of the form to that button.

获取或设置点击,当用户按下<大骨节病> ESC 键。

Gets or sets the button control that is clicked when the user presses the Esc key.

如果你没有一个取消按钮,那么你就需要添加一个的KeyDown 处理程序,并检查Esc键在于:

If you don't have a cancel button then you'll need to add a KeyDown handler and check for the Esc key in that:

private void Form_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Escape)
    {
        this.Close();
    }
}

您也必须设置的 的KeyPreview 属性真实的。

You will also have to set the KeyPreview property to true.

获取或设置指示事件被传递给具有焦点的控制之前的形式是否会接收按键事件的值。

Gets or sets a value indicating whether the form will receive key events before the event is passed to the control that has focus.

然而,如Gargo在他指出答案这将意味着按<大骨节病> ESC 中止编辑的对话也将关闭该对话框的作用在控制。为了避免覆盖 ProcessDialogKey 方法如下:

However, as Gargo points out in his answer this will mean that pressing Esc to abort an edit on a control in the dialog will also have the effect of closing the dialog. To avoid that override the ProcessDialogKey method as follows:

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

这篇关于如何按ESC键使时一种形式结束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆