Click here to Skip to main content
15,902,299 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a form say Form1 What I have to do is when user presses Close button on title bar of the form it should allow him choice whether to exit or not;If he presses No the application should keep running.

This functionality would work fine example from Exit menu or button but people tend to press close button on title bar



I have written the following code:---

C#
private void Form1_FormClosing(object sender, FormClosedEventArgs e)
{
DialogResult dr = MessageBox.Show("Do you want to quit", "Exit",MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk);
           if (dr == DialogResult.No)
           {
               return;
               //Code Trying to prevent closing of form but failed

           }
}


it's no meaning to give:-
C#
if (dr == DialogResult.Yes)
           {
               this.Close();
                //Form will close even without this...

           }

C#



Thanks in Advance.....
Posted

Try:
C#
private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
    {
    if (MessageBox.Show("Close?", "Close main form", MessageBoxButtons.YesNo) == DialogResult.No)
        {
        e.Cancel = true;
        }
    }
 
Share this answer
 
Comments
Mantu Singh 22-Oct-11 10:42am    
Thanks a lot......! that worked...
OriginalGriff 22-Oct-11 10:44am    
You're welcome!
When you get the FormClosing event the then the form is already going to close, if you called this.Close() outside of the event for example, then your event would be fired.

It actually seems like your using the FormClosed event, by this point it's too late to stop the form from closing. You want to use the FormClosing event which takes the FormClosingEventArgs which you can use to stop the form from closing, or change the CloseReason property.

You can then stop the form from closing buy setting e.Cancel = true
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900