I got the problem. In fact, this is the correct phenomenon.
When we click to exit, the code enters the OnFormClosing method, where AskToSave() is called.
protected override void OnFormClosing(FormClosingEventArgs e)
{
AskToSave();
}
We did not perform any check on its return value. No matter the user chooses to exit or save in the file explorer dialog, this method can be executed normally, and there is no reason to prevent the program from closing normally.
If you want the user to think about whether to exit, you can pop up a MessageBox:
protected override void OnFormClosing(FormClosingEventArgs e)
{
AskToSave();
var window = MessageBox.Show(
"Close the window?",
"Are you sure?",
MessageBoxButtons.YesNo);
e.Cancel = (window == DialogResult.No);
}
Update(6/23):
If you don't want to use an additional MessageBox, we need to add a field and modify several codes.
private bool isCancel = false;
protected override void OnFormClosing(FormClosingEventArgs e)
{
AskToSave();
e.Cancel = isCancel;
}
In the SaveAs() method:
if (saveFileDialog1.ShowDialog() != DialogResult.OK)
{
isCancel = true;
Debug.WriteLine("This is hemanth debug2");
return false;
}
else if (saveFileDialog1.ShowDialog() == DialogResult.Cancel)
{
Debug.WriteLine("This is hemanth debug3");
return true;
}
I have a question here, saveFileDialog1.ShowDialog() != DialogResult.OK
includes saveFileDialog1.ShowDialog() == DialogResult.Cancel
, so the code in else if will never be executed. Is this an unexpected error?
In the AskToSave() method:
if (dr != DialogResult.Yes)
{
isCancel = false;
return;
}
If there are still any problems with the code, please feel free to let me know.
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.