views:

165

answers:

2
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    if (e.CloseReason == CloseReason.UserClosing)
    {
        if (MessageBox.Show(this, "Do you really want to close?", "Close?", 
                            MessageBoxButtons.YesNo) == DialogResult.No)
        {
            e.Cancel = true;
        }
    }
}

So when I want to close the application clicking the close button the message box is shown as it should, then I chose no. Then the line e.Cancel = true is executed and the form is not closed.

Now the thing is, after this if i close the application from task manager the close reason is UserClosing !!! Why? Shouldn't it be TaskManagerClosing?

+1  A: 

I found a thread with an answer by our very own nobugz:

Windows Forms cannot detect that the close reason came from the Task Manager. So it automatically translates CloseReason.None to CloseReason.TaskManagerClosing. Problem is, once you tried to close with the "X", the CloseReason is set to UserClosing and doesn't get reset back to None if you cancel the close. Sloppy.

And next to it, an explanation by another user on how to change e.CloseReason's value to None using Reflection (since it is read-only), to work-around this problem (this should be applied when setting e.Cancel to True):

FieldInfo fi = typeof(Form).GetField("closeReason", BindingFlags.Instance | BindingFlags.NonPublic);

fi.SetValue(this, CloseReason.None);
M.A. Hanin
It works. Great.
Samir
A: 

See the answer to this question which uses CloseReason.TaskManagerClosing to catch the same.

KMan
The code in the link detects whether the close is due to a button click or from windows x button click. Using a bool property to detect is ok here. But how to detect TaskManager closing?
Samir