Task Manager closure not detected a second time in WinForms application

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

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

Now the fact is that after this, if I close the application from the task manager, the reason for closing is UserClosing !!! What for? Shouldn't be TaskManagerClosing?

+4
source share
3 answers

I found thread with the answer to our own nobugz :

Windows Forms cannot detect that the reason was caused by the Task Manager. So this automatically translates CloseReason.None to CloseReason.TaskManagerClosing. The problem is that when you tried to close with "X" the CloseReason parameter is set to UserClosing and does not get reset back to None if you cancel the close. Sloppy.

And next to it is another user's explanation on how to change the value of e.CloseReason to None using Reflection (since it is read-only) to get around this problem (this should apply when setting up e.Cancel to True):

 FieldInfo fi = typeof(Form).GetField("closeReason", BindingFlags.Instance | BindingFlags.NonPublic); fi.SetValue(this, CloseReason.None); 
+2
source

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

0
source

Just translating your code into 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

0
source

Source: https://habr.com/ru/post/1305821/


All Articles