Question

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?

Was it helpful?

Solution

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);

OTHER TIPS

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

Just the translation of you code in VB:

Imports System.Reflection
Private Sub ResetCloseReason()
  Dim myFieldInfo As FieldInfo
  Dim myType As Type = GetType(Form)
  myFieldInfo = myType.GetField("closeReason", BindingFlags.NonPublic Or _
                    BindingFlags.Instance Or BindingFlags.Public)
  myFieldInfo.SetValue(Me, CloseReason.None)

End Sub

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top