Task manager close is not detected second time in a WinForms Application

强颜欢笑 提交于 2019-12-22 08:26:38

问题


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:


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



回答2:


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




回答3:


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



来源:https://stackoverflow.com/questions/2565041/task-manager-close-is-not-detected-second-time-in-a-winforms-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!