I am developing a WinForms (.NET 4.7.2) application with Telerik WinForm (2019.2.618.40) controls.
On click of Close Box [x] icon on top tight of the window, I would like to ask for user confirmation and if YES only then close the app.
Following code works well, it closes the window, but it is not closing process (I can still see the app in Task Manager).
I believe I need to call Application.Exit();
to kill the app process. But When I call that Closing Event is fired twice and I get confirmation window twice and gets following error
System.InvalidOperationException: 'Collection was modified; enumeration operation may not execute.'
How do I correct my closing event so that I can ask for user confirmation and close the windows as well as exit application cleanly from Task manager as well?
My Base Form
public class BaseForm : Telerik.WinControls.UI.RadForm
{
public BaseForm()
{
this.FormClosing += new FormClosingEventHandler(Form_Closing);
}
public void Form_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
RadMessageBox.SetThemeName("Material");
DialogResult dialogResult = RadMessageBox.Show(
this,
"Are you sure, you want to exit out of the application? Any unsaved data will be lost!",
"Application Name",
MessageBoxButtons.YesNo,
RadMessageIcon.Question,
MessageBoxDefaultButton.Button2,
RightToLeft.No);
if (dialogResult == DialogResult.Yes)
{
e.Cancel = false;
//Application.Exit();
}
else if (dialogResult == DialogResult.No)
{
e.Cancel = true;
}
base.OnClosing(e);
}
//....
//....
//....
}
Update
instead of FormClosign Event if I use FormClosed event, Application.Exit()
works fine, but on confirmation message if I click NO it is still closing app.
this.FormClosed += new FormClosedEventHandler(App_kill);
App Kill Method (Cannot handle DialogResult.No response)
private void App_kill(object sender, FormClosedEventArgs e)
{
if (e.CloseReason == CloseReason.UserClosing)
{
RadMessageBox.SetThemeName("Material");
DialogResult dialogResult = RadMessageBox.Show(
this,
"Are you sure, you want to exit out of the application? Any unsaved data will be lost!",
"Close Application",
MessageBoxButtons.YesNo,
RadMessageIcon.Question,
MessageBoxDefaultButton.Button2,
RightToLeft.No);
if (dialogResult == DialogResult.Yes)
{
Application.Exit();
}
if (dialogResult == DialogResult.No)
{
//e.Cancel = true;
}
}
}
Thanks to nihique posted here https://stackoverflow.com/a/13459878/942855 and also pointed by MickyD in this question comments.
Apparently there is no issue with my closing event. When I redirect from Form-A to Form-B, I had to do the following wiring and then it worked like a charm
var newform = new myNewForm();
newform.Closed += (s, args) => this.Close();
this.Hide();
newform.Show();