退出按钮以关闭 C# 中的 Windows 窗体窗体 [英] Escape button to close Windows Forms form in C#

查看:31
本文介绍了退出按钮以关闭 C# 中的 Windows 窗体窗体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了以下方法:

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

但它不起作用.

然后我尝试了这个:

protected override void OnKeyDown(KeyEventArgs e)
{
    base.OnKeyDown(e);
    if (e.KeyCode == Keys.Escape)
        this.Close();
}

仍然没有任何效果.

我的 Windows 窗体表单属性上的 KeyPreview 设置为 true...我做错了什么?

The KeyPreview on my Windows Forms form properties is set to true... What am I doing wrong?

推荐答案

无论是否正确分配事件处理程序、KeyPreviewCancelButton 等,这都将始终有效:

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);
}

这篇关于退出按钮以关闭 C# 中的 Windows 窗体窗体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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