简体   繁体   中英

prohibit user from closing the form

I have a main form called Form_Main , when somebody wants to close it, it will close the entire application (by entire application I mean quitting other forms as well). Therefore I prepared a yes/no MessageBox that ask users if they really want to quit the form. Here's where I'm at:

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

The "OK" button works. But when users clicks "Cancel", Form_Main is closed, but the application is still running (other forms are untouched). What should I replace //does nothing with?

Use the FormClosing event (instead of FormClosed ), and then set 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);
}

The FormClosing event occurs before the form actually closes, so you still have a chance to cancel it. By the time you get to the FormClosed event, it's too late.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM