No matter how a winforms application closes the FormClosing event always reports the closereason as "userclosing"
My application needs to log how a it was closed. Since the FormClosingEventArgs in the FormClosing event supports enumerated closing values such as
- WindowsShutdown
- TaskManagerClosing
- UserClosing
- MdiFormClosing
- None
it makes sense to simply log that value as the form shuts down. But... no matter how I close the form it always reports CloseReason.UserClosing. I have already tried using reflection (based on the suggestion in Task manager close is not detected second time in a WinForms Application ) - but I get the same results as reported by FormClosingEventArgs
I wrote a test app
Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
Dim fi As FieldInfo
Dim ty As Type = GetType(Form)
fi = ty.GetField("closeReason", BindingFlags.NonPublic Or BindingFlags.Instance Or BindingFlags.Public)
Dim cr As String = fi.GetValue(Me).ToString()
My.Computer.FileSystem.WriteAllText("d:\closetest.log", cr & vbCrLf, True)
My.Computer.FileSystem.WriteAllText("d:\closetest.log", e.CloseReason.ToString & vbCrLf, True)
End Sub
The above code always reports UserClosing in both the FormClosingEventArgs as well as in the reflected value. It doesn't matter how I close the form - including closing via the TaskManager. This is really frustrating - it's as though MS has turned this capability off in the OS altogether. My issue is that I have an application that appears to close on it's own and leaves no trace in my own logging, nor in the Windows Application logs - nothing, nada. So I am suspicious of some external event and need to see if this might log it...