【VB.NET】Windowsの起動と終了の時間を表示 | 備忘録 (。・_・。)ノ
Imports Microsoft.Win32
'ShowInTaskbar -> False
'WindowsState -> Minimized
Public Class Form1
    Dim strOutPut As String = My.Application.Info.DirectoryPath & "\LogOn.txt"

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Try
            Using writer As New System.IO.StreamWriter(strOutPut, False, System.Text.Encoding.GetEncoding("shift_jis"))
                writer.WriteLine("起動," & Now())
            End Using

            AddHandler SystemEvents.SessionEnding, AddressOf SystemEvents_SessionEnding

        Catch ex As System.Exception
            MsgBox(ex.Message)
            End
        End Try
    End Sub

    Private Sub SystemEvents_SessionEnding(ByVal sender As Object, ByVal e As SessionEndingEventArgs)
        'シャットダウン
        If e.Reason = SessionEndReasons.SystemShutdown Then
            Dim strInPut As New System.IO.StreamReader(strOutPut, System.Text.Encoding.Default)
            Dim strLogOn As String
            strLogOn = strInPut.ReadLine()
            strInPut.Close()

            strOutPut = My.Application.Info.DirectoryPath & "\" & Format(Now(), "yyyyMM") & ".csv"
            Using writer As New System.IO.StreamWriter(strOutPut, True, System.Text.Encoding.GetEncoding("shift_jis"))
                writer.WriteLine(Environment.UserName & "," & strLogOn & ",終了," & Now())
            End Using
        End If
    End Sub
End Class