2014-12-13 81 views
2

程序意外結束執行代碼這是我在執行,將設置用戶的狀態爲脫機狀態,如果他們正確地關閉程序的代碼代碼:如何運行在VB.net

Private Sub frmMainForm_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing 
    If MsgBox("Are you sure you want to exit this application?", MsgBoxStyle.Question + MsgBoxStyle.YesNo, "Exit?") = MsgBoxResult.Yes Then 

     Update_UserStatus(iUserID, 0) 'update the Status of user to Offline 

     End 
    End If 
    e.Cancel = True 
End Sub 

Public Sub Update_UserStatus(iUserID As Integer, isOnline As Integer) 
    Dim strQ As String = String.Empty 

    strQ = "update tbl_user set isOnline = " & isOnline & " where ID = " & iUserID & "" 

    Try 
     If con.State = ConnectionState.Closed Then con.Open() 

     cmd = New MySqlCommand(strQ, con) 
     cmd.ExecuteNonQuery() 
     cmd = Nothing 


    Catch ex As Exception 
     MsgBox(ex.Message) 
    Finally 
     con.Close() 
    End Try 

End Sub 

但是當程序意外關閉時,如何運行這段代碼,例如當我打開任務管理器並強制關閉程序時。謝謝你在前進

回答

0

您可以處理應用程序threadexception事件

Public Shared Sub Main() 
' Add the event handler for handling UI thread exceptions to the event. 
     AddHandler Application.ThreadException, AddressOf ErrorHandlerForm.Form1_UIThreadException 
End Sub 

' Handle the UI exceptions by showing a dialog box, and asking the user whether 
     ' or not they wish to abort execution. 
     Private Shared Sub Form1_UIThreadException(ByVal sender As Object, ByVal t As ThreadExceptionEventArgs) 
      Dim result As System.Windows.Forms.DialogResult = _ 
       System.Windows.Forms.DialogResult.Cancel 
      Try 
       result = ShowThreadExceptionDialog("Windows Forms Error", t.Exception) 
      Catch 
       Try 
        MessageBox.Show("Fatal Windows Forms Error", _ 
         "Fatal Windows Forms Error", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Stop) 
       Finally 
        Application.Exit() 
       End Try 
      End Try 

      ' Exits the program when the user clicks Abort. 
      If result = DialogResult.Abort Then 
       Application.Exit() 
      End If 
     End Sub 

在這裏你可以找到一個Source Code有關如何使用它