Click here to Skip to main content
15,921,990 members
Please Sign up or sign in to vote.
3.00/5 (2 votes)
See more:
hi for window close button, what is the code to ask for exit before closing the form?if user accepts,close the form,if not, stay in window.

thanks
Posted
Updated 5-Mar-12 12:56pm
v2

Hello

In FormClosing event

C#
private void MyForm_FormClosing(object sender, FormClosingEventArgs e)
{
    if (MessageBox.Show("Are you sure to close the form?",
          "Question", 
              MessageBoxButtons.YesNo, 
                   MessageBoxIcon.Question) != System.Windows.Forms.DialogResult.Yes)
        e.Cancel = true;
}
 
Share this answer
 
v2
Comments
FM7 5-Mar-12 18:58pm    
sepasgozaram shahin jan
Shahin Khorshidnia 5-Mar-12 19:04pm    
Mer30
Sergey Alexandrovich Kryukov 5-Mar-12 22:09pm    
In general case, you should also check e.CloseReason, like:

if (e.CloseReason == CloseReason.UserClosing) //... the rest of your code in the body of the handler method.

MyForm_FormClosing name is a violation of Microsoft naming conventions. This is auto-generated names. All such names should be renamed to something semantic. For answers and many other cases, it's the best to use anonymous handlers (no name, no problem :-)

this.FormClosing += (sender, eventArgs) => { PreventClosing(s); } //no need to use unused sender, for example...

So, overall, how can I vote? OK, a 4.

Cheers,
--SA
Shahin Khorshidnia 6-Mar-12 5:07am    
Thanks Sa firstly for the perfect criticism, secondly for upvoting.
I had not regarded the point, and yes it's better to use an anonymous handler.
Sergey Alexandrovich Kryukov 7-Mar-12 0:57am    
I'm very happy to hear that from you.
Thanks for reading carefully and understanding.
Cheers,
--SA
[Spam content removed, offender's account disabled — SA]
 
Share this answer
 
v2
Comments
FM7 5-Mar-12 18:56pm    
what is that!!?
Shahin Khorshidnia 5-Mar-12 18:57pm    
Don't you know? It's s spam!
Sergey Alexandrovich Kryukov 5-Mar-12 22:03pm    
Next time, please mark is as spam (red flag) and also report to:
http://www.codeproject.com/Forums/1652005/Spam-Watch.aspx
--SA
Shahin Khorshidnia 6-Mar-12 4:53am    
I did!
:D
Sergey Alexandrovich Kryukov 7-Mar-12 1:03am    
Great!

I remember very well that it's better to destroy bombers and fighter on the airports; when they launch, it's way more difficult.

--SA

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