禁止用户关闭表单

Hen*_*ian 2 c# forms

我有一个主要的表单Form_Main,当有人想关闭它时,它会关闭整个应用程序(整个应用程序,我的意思是退出其他形式).因此,我准备了一个是/否MessageBox,询问用户是否真的想要退出表单.这是我在的地方:

private void Form_Main_FormClosed(object sender, FormClosedEventArgs e)
{
      DialogResult result = MessageBox.Show("Are you sure?", "Confirmation", MessageBoxButtons.OKCancel);
      if (result == DialogResult.OK)
      {
          Environment.Exit(1);
      }
      else
      {
          //does nothing
      }
}
Run Code Online (Sandbox Code Playgroud)

"确定"按钮有效.但是当用户单击"取消"时,Form_Main关闭,但应用程序仍在运行(其他形式未触及).我该怎么替换//does nothing

Gra*_*ICA 6

使用FormClosing事件(而不是FormClosed),然后设置e.Cancel = true:

private void Form_Main_FormClosing(object sender, FormClosingEventArgs e)
{
    var result = MessageBox.Show("Are you sure?", "Confirmation", MessageBoxButtons.OKCancel);

    e.Cancel = (result != DialogResult.OK);
}
Run Code Online (Sandbox Code Playgroud)

FormClosing发生事件之前的形式实际上关闭,所以你仍然有机会取消.当你参加FormClosed活动时,为时已晚.