C# 任务栏按钮右键单击:windows窗体中的自定义菜单

C# 任务栏按钮右键单击:windows窗体中的自定义菜单,c#,windows,winforms,C#,Windows,Winforms,我不希望窗体在右键单击任务栏按钮时弹出的菜单中单击“关闭窗口”选项时退出。相反,我希望将应用程序最小化到系统托盘。 如何更改“关闭窗口”的行为 添加对OnFormClosing的覆盖,并查看事件参数的CloseReason。也许是这样的: protected override OnFormClosing(FormClosingEventArgs e) { if (e.CloseReason == CloseReason.UserClosing) { e.Cance

我不希望窗体在右键单击任务栏按钮时弹出的菜单中单击“关闭窗口”选项时退出。相反,我希望将应用程序最小化到系统托盘。
如何更改“关闭窗口”的行为

添加对
OnFormClosing
的覆盖,并查看事件参数的
CloseReason
。也许是这样的:

protected override OnFormClosing(FormClosingEventArgs e)
{
    if (e.CloseReason == CloseReason.UserClosing)
    {
        e.Cancel = true;
        this.Hide();
    }
    else
    {
        this.Close();
    }
}

这样,用户无法关闭表单(仅隐藏表单),但Windows仍可以出于其他原因关闭表单(如关机)。

谢谢!工作起来很有魅力。我不得不将参数改为OnFormClosing(formclosingerventargs e),以便正确地覆盖它。@arhud:关于签名,你是对的。这可能是一个事件。你需要有一个很好的理由这样做,因为当操作系统应用程序操作不按要求做时,用户往往会感到恼火!