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

怎甘沉沦 提交于 2019-12-05 16:50:13
M.A. Hanin

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);
KMån

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

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