I am currently developing a C# Windows Form Application.
After the user has login through the loginForm, it will be brought to the mainForm.
I would like to code it in a way that after the user click the cross on the title bar in the mainForm, there would be a prompt asking the user “This will close the application. Confirm?”
followed by a yes and no button.
If yes, another box will be displayed, “Application Closed!”
If no, the messagebox will just close and the application will continue running.
My current code is :
private void mainForm_FormClosing(object sender, FormClosingEventArgs e)
{
if (MessageBox.Show("This will close down the whole application. Confirm?", "Close Application", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
MessageBox.Show("The application has been closed successfully.", "Application Closed!", MessageBoxButtons.OK);
System.Windows.Forms.Application.Exit();
}
else
{
this.Activate();
}
}
however it does not work.
Firstly I have no idea why the messagebox pops up twice in order for the whole thing to close.
Secondly if i click no, the form closes as well and I am not able to bring it back.
To cancel the closing of the form, in your else statement you need
e.Cancel = true;.You don’t need the explicit Exit in your true case.
Give this a try
I assume your second MessageBox to say it has closed if for testing purposes only.
You probably only want.
Notice the statement checks to see if they didn’t hit yes, rather than if they hit cancel. This means that if they hit the x on the dialog box it won’t be counted as a confirmation.
EDIT: If mainForm isn’t the main form
Okay, I think I’ve got what you’re asking now.
What I would do is put the code I have in my second code block above in the FormClosing, and then in the FormClosed event handler have this