共用方式為


HOW TO:在應用程式啟動或關閉時記錄訊息

更新:2007 年 11 月

您可以使用 My.Application.Log 和 My.Log 物件,記錄在應用程式中發生的事件資訊。這個範例會顯示如何使用具有 Startup 和 Shutdown 事件的 My.Application.Log.WriteEntry 方法,寫入追蹤資訊。

若要存取應用程式的事件處理常式程式碼

  1. 在 [方案總管] 中選取專案。在 [專案] 功能表上,選擇 [屬性]。

  2. 按一下 [應用程式] 索引標籤。

  3. 按一下 [檢視應用程式事件] 按鈕,開啟 [程式碼編輯器]。

    這會開啟 ApplicationEvents.vb 檔案。

若要在應用程式啟動時記錄訊息

  1. 在程式碼編輯器中開啟 ApplicationEvents.vb 檔案。在 [一般] 功能表上,選擇 [MyApplication 事件]。

  2. 在 [宣告] 功能表上,選擇 [啟動]。

    應用程式會在主應用程式執行之前引發 Startup 事件。

  3. 將 My.Application.Log.WriteEntry 方法加入至 Startup 事件處理常式。

    My.Application.Log.WriteEntry("Application started at " & _
        My.Computer.Clock.GmtTime.ToString)
    

若要在應用程式關閉時記錄訊息

  1. 在程式碼編輯器中開啟 ApplicationEvents.vb 檔案。在 [一般] 功能表上,選擇 [MyApplication 事件]。

  2. 在 [宣告] 功能表上,選擇 [關機]。

    應用程式會在主應用程式執行之後 (但是在關閉之前) 引發 Shutdown 事件。

  3. 將 My.Application.Log.WriteEntry 方法加入至 Shutdown 事件處理常式。

    My.Application.Log.WriteEntry("Application shut down at " & _
        My.Computer.Clock.GmtTime.ToString)
    

範例

您可以使用 [專案設計工具],在「程式碼編輯器」中存取應用程式事件。如需詳細資訊,請參閱 HOW TO:處理應用程式事件 (Visual Basic)

Private Sub MyApplication_Startup( _
    ByVal sender As Object, _
    ByVal e As ApplicationServices.StartupEventArgs _
) Handles Me.Startup
    My.Application.Log.WriteEntry("Application started at " & _
        My.Computer.Clock.GmtTime.ToString)
End Sub

Private Sub MyApplication_Shutdown( _
    ByVal sender As Object, _
    ByVal e As System.EventArgs _
) Handles Me.Shutdown
    My.Application.Log.WriteEntry("Application shut down at " & _
        My.Computer.Clock.GmtTime.ToString)
End Sub

請參閱

工作

HOW TO:處理應用程式事件 (Visual Basic)

概念

在 Visual Basic 中使用應用程式記錄檔

參考

My.Log 物件

My.Application.Log 物件

WriteEntry 方法 (My.Application.Log 和 My.Log)

WriteException 方法 (My.Application.Log 和 My.Log)