Reputation: 1779
I am using following code on closing event of my Windows forms application form:
private void Main_FormClosing(object sender, FormClosingEventArgs e)
{
DialogResult dr = MessageBox.Show("Are you sure you want to quit?", "Leaving App",MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (dr == DialogResult.No)
{
return;
}
else
Application.Exit();
}
But the problem is, whenever user clicks Yes the application ends but when user clicks No, the application is still running but the form hides. How can I keep form visible when user clicks No?
Update
Another problem I am facing is that, when I click Yes, the MessageBox displays again and then I click Yes the application exits. Why its displaying for two times?
Upvotes: 5
Views: 10126
Reputation: 21
If you just put the following code into the click event for your exit button, it works fine :)
DialogResult quit = MessageBox.Show("Are you sure you want to quit?", "Quit", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
if (quit == DialogResult.Yes) this.Close();
Upvotes: 1
Reputation: 11
I am Akhilavishnu, for more help please mail me [email protected]. Please put these lines of codes in your application it works well happy coding.
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if(MessageBox.Show("Are you sure that you want to exit",
MessageBoxButtons.YesNo,
MessageBoxIcon.question) == DialogResult.No)
{
e.Cancel=true;
}
}
//in formclose event
private void Form1_FormClosed(object sender,FormClosedEventArgs e)
{
Application.Exit();
}
Upvotes: 1
Reputation: 51
I know it is not the correct way but it will result as you want.
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if(MessageBox.Show("Are you sure you want to quit?", "Leaving App", MessageBoxButtons.YesNo).ToString()=="No")
e.Cancel = true;
}
Because of ToString() method will provide the result of the dialog box when used with a message box.
Upvotes: 1
Reputation: 11577
you need to cancel the exit using e.Cancel = true;
in your event Main_FormClosing
to stop from closing
Upvotes: 2
Reputation: 43300
private void Form1_Closing(Object sender, CancelEventArgs e) {
if (!isDataSaved) {
e.Cancel = true;
MessageBox.Show("You must save first.");
}
else {
e.Cancel = false;
MessageBox.Show("Goodbye.");
}
}
Upvotes: 7
Reputation: 17600
You don't have to call Application.Exit()
because if you do not cancel closing it program will exit itself. Below is corrected code that is working:
private void Main_FormClosing(object sender, FormClosingEventArgs e)
{
DialogResult dr = MessageBox.Show("Are you sure you want to quit?", "Leaving App",MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (dr == DialogResult.No)
{
e.Cancel = true;
}
}
Upvotes: 9