Zebra0.com

csharp richtext

Exit and Close

If the user selects mnuExit or closes with the X in the top right corner, we need to ask if they want to save. In either case, they could select cancel.

If they select cancel, we must not close. For Exit, that is not a problem.
To write the code for closing select the form in the design mode, then from properties click the events button (the lightening bolt) and select FormClosing as the event. Write the code as shown below.

private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
   // Ask if they want to save. it returns true if the user chose to cancel.
   Boolean cancel = AskToSave();
   if (!cancel) Close();
}
      
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
   // Ask if they want to save. it returns true if the user chose to cancel.
   // The FormClosingEventArgs e has a cancel property. Setting it to true cancels the close event.
   e.Cancel = AskToSave();
}

To Do: Make sure this works before proceeding.

End of lesson, Next lesson: That is the last C# lesson in this course.