【问题标题】:Application.Exit() not working properlyApplication.Exit() 无法正常工作
【发布时间】:2016-12-25 10:24:37
【问题描述】:

我有一个单独的窗体供用户选择背景音乐,除非应用程序关闭,否则它将一直保留在那里。我使用代码阻止用户关闭音乐表单:

private void Music_FormClosing(object sender, FormClosingEventArgs e)
    {
        e.Cancel = true;
    }

在我的主 Program.cs 中,我运行一个名为 login 的页面,如下所示:

Application.Run(new Login());

我在我的所有表单中也有一个 FormClosed 事件,它会在按下十字后关闭整个程序

private void Login_FormClosed(object sender, FormClosedEventArgs e)
    {
        Application.Exit();
    }

但是,在我添加了用户无法关闭音乐表单的代码后,我的应用程序只能在登录页面中按十字键退出,这是程序运行的开始主页(该应用程序过去可以通过按十字退出我的所有表单)

我想知道是否有任何方法可以让我正确退出我的应用程序,或者让用户无法在不影响其他表单关闭的情况下关闭音乐表单。谢谢

【问题讨论】:

  • 您无法使用音乐表单关闭,因为您正在使用 e.Cancel = true; 取消该操作.. 不是吗?
  • 是的,我的意思是让用户无法关闭音乐表单,只能通过关闭主表单来关闭
  • 然后将Application.Exit(); 替换为Environment.Exit(0);。因为Application.Exit(); 提高了Music_FormClosing 这使它失败了。

标签: c# winforms exit


【解决方案1】:

Music_FormClosing 中的代码阻止您的应用程序退出。要获得所需的行为(防止用户关闭音乐表单),您可以利用 FormClosingEventArgs CloseReason 属性:

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

【讨论】:

  • 错误提示“CloseReason”是一种类型,在给定的上下文中无效
  • 只是拼写错误(SO 编辑器输入)。正如我在答案中提到的,它是传递的FormClosingEventArgs 的属性。
猜你喜欢
  • 2010-10-07
  • 2016-12-01
  • 1970-01-01
  • 2016-09-01
  • 2012-07-11
  • 2018-04-08
  • 2017-04-20
  • 2018-10-02
  • 2016-09-04
相关资源
最近更新 更多