如何:当应用程序启动或关闭时记录消息

更新:2007 年 11 月

可以使用 My.Application.Log 和 My.Log 对象记录有关应用程序中发生的事件的信息。此示例演示了如何使用具有 Startup 和 Shutdown 事件的 My.Application.Log.WriteEntry 方法来编写跟踪信息。

访问应用程序的事件处理程序代码

  1. 在“解决方案资源管理器”中选择一个项目。在“项目”菜单上,选择“属性”。

  2. 单击“应用程序”选项卡。

  3. 单击“查看应用程序事件”按钮打开代码编辑器。

    此操作将打开 ApplicationEvents.vb 文件。

当应用程序启动时记录消息

  1. 在代码编辑器中保持 ApplicationEvents.vb 文件的打开状态。在“常规”菜单中选择“MyApplication 事件”。

  2. 在“声明”菜单中选择“启动”。

    主应用程序运行之前,应用程序将引发启动事件。

  3. 将 My.Application.Log.WriteEntry 方法添加到 Startup 事件处理程序中。

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

当应用程序关闭时记录消息

  1. 在代码编辑器中保持 ApplicationEvents.vb 文件的打开状态。在“常规”菜单中选择“MyApplication 事件”。

  2. 在“声明”菜单中选择“关闭”。

    在主应用程序运行之后但在关闭之前,应用程序将引发关闭事件。

  3. 将 My.Application.Log.WriteEntry 方法添加到 Shutdown 事件处理程序中。

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

示例

可以使用“项目设计器”来访问代码编辑器中的应用程序事件。有关更多信息,请参见如何:处理应用程序事件 (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

请参见

任务

如何:处理应用程序事件 (Visual Basic)

概念

使用 Application 日志 (Visual Basic)

参考

My.Log 对象

My.Application.Log 对象

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

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