[英]VB.NET always gives a closereason as userclosing
無論winforms應用程序如何關閉,FormClosing事件始終將關閉原因報告為“用戶關閉”
我的應用程序需要記錄它如何關閉。 由於FormClosing事件中的FormClosingEventArgs支持枚舉的關閉值,例如
在表單關閉時簡單地記錄該值是有意義的。 但是...無論我如何關閉表單,它始終會報告CloseReason.UserClosing 。 我已經嘗試過使用反射(基於在WinForms應用程序中第二次未檢測到Task Manager close中的建議)-但是得到的結果與FormClosingEventArgs報告的結果相同
我寫了一個測試應用
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
as well as in the reflected value. 上面的代碼始終在和反射值中都報告UserClosing 。 無論如何關閉表單都沒關系-包括通過TaskManager關閉。 這確實令人沮喪-好像MS完全在OS中關閉了此功能。 我的問題是我有一個似乎自己關閉的應用程序,在我自己的日志記錄和Windows應用程序日志中均未留下任何痕跡-沒什么,納達。 因此,我對某些外部事件感到懷疑,需要查看它是否會記錄下來...
您可以這樣:
Dim CloseByMyButton As Boolean = False
Private Sub btnClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClose.Click
'If this form is child form call this
CloseByMyButton = True
me.Close
'if this form is main form call this
'Application.exit
End Sub
Private Sub MessageForm_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
'may be e.CloseReason = CloseReason.TaskManagerClosing must first line in this sub procedure, because it is too quick
If e.CloseReason = CloseReason.TaskManagerClosing Then
MessageBox.Show("You close from Task Manager")
ElseIf e.CloseReason = CloseReason.ApplicationExitCall Then
MessageBox.Show("You close by exit application")
ElseIf e.CloseReason = CloseReason.UserClosing Then
If CloseByMyButton = True Then
MessageBox.Show("You close by UserClosing With btnClose_Click")
Else
MessageBox.Show("You close by UserClosing Normally")
End If
Else
MessageBox.Show("You close by Others")
End If
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.