【问题标题】:How do I disable ALT+F4 from closing but pressing H will close the program如何禁用 ALT+F4 关闭但按 H 将关闭程序
【发布时间】:2014-03-14 18:25:37
【问题描述】:

例如让这个工作:

protected override bool ProcessDialogKey(Keys keyData)
{
    if (keyData == Keys.H)
    {
        this.Close();
        return true;
    }
    else
    {
        return base.ProcessDialogKey(keyData);
    }
}

当我禁用 Alt+f4 时,我无法使用 e.Cancel = true;,因为它会禁止按 H 键关闭程序。

【问题讨论】:

  • 您必须禁用系统菜单项而不是取消关闭。
  • 当用户点击关闭按钮或从上下文菜单中选择关闭时你想做什么?

标签: c# winforms


【解决方案1】:

试试这个:

解决方案 1:

protected override bool ProcessDialogKey(Keys keyData)
    {
        if (keyData == Keys.H)
        {
            this.Close();
            return true;
        }
        else if (keyData == Keys.Alt | keyData == Keys.F4)
        {
            return base.ProcessDialogKey(keyData);
        }
        return true;
    }

解决方案 2:

 private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Alt | e.KeyCode==Keys.F4)
        {
            e.Handled = true;
        }
        else if (e.KeyCode == Keys.H)
        {
            this.Close();
        }
    }

【讨论】:

  • @Downvoter:你能解释一下这个问题吗?
【解决方案2】:

试试这个:

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    e.Cancel = (e.CloseReason == CloseReason.UserClosing);
}

只有当用户试图通过用户界面关闭表单时,您才会取消关闭。

检查这个:How to Disable Alt + F4 closing form?

【讨论】:

  • @SriramSakthivel 你是对的。 Sudhakar 的答案是正确的,假设您允许用户使用关闭按钮关闭表单。
  • 是的,也使用关闭按钮和 Windows 上下文菜单。如果用户想阻止这些,这也是要走的路:)
【解决方案3】:

设置一些全局变量关闭怎么样?

bool closeForm = false;
protected override bool ProcessDialogKey(Keys keyData)
{
    if (keyData == Keys.H)
    {
        closeForm = true;
        this.Close();
        return true;
    }
    else
    {
        return base.ProcessDialogKey(keyData);
    }
}

在您的 FormClosing 事件中,只需像这样检查变量

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    if (!closeForm)
       e.Cancel = true;
}

【讨论】:

    猜你喜欢
    • 2010-09-06
    • 2012-05-09
    • 1970-01-01
    • 2018-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-09
    • 2019-12-02
    相关资源
    最近更新 更多