Determine the Time Since the Last Boot Up in Visual Basic

Introduction:

This article describes an approach used to determine the time of the last system boot up and to display the time elapsed since boot up.  The application uses element of the System.Management library to run a select query against Win32_OperatingSystem; the application also display the amount of elapsed time since system boot up by comparing the boot up time against the current time; the elapsed time is updated every 1000 milliseconds whilst the application is running. A TimeSpan object is used to calculate the difference between the current time and the boot up time.

Time-Since-Last-Boot-in-windows8.gif

Figure 1:  The Application

Getting Started:

In order to get started, unzip the included project and open the solution in the Visual Studio 2008 environment.   In the solution explorer, you should note these files (Figure 2):

TimeSinceLastBootVB2-in-windows8.gif

Figure 2:  Solution Explorer

As you can see from Figure 2; there is a single Win Forms project containing a single form.  All code required of this application is included in this form's code.

The Main Form (Form1.vb).

The main form of the application, Form1, contains all of the code necessary.  The form contains

If you'd care to open the code view up in the IDE you will see that the code file begins with the following library import:

Imports System.Management

 

Following the imports, the class is defined:

 

Public Class Form1

 

Next up, a local variable is defined:
 

    ' local member variable

    Private dtBootTime As New DateTime()

 

This variable is used to store the last boot up time; this value is set when the application starts and is used in each subsequent evaluation the elapsed time (in response to a timer tick event).

The next section of code is the form's constructor; the only addition to the default was to enable the timer used to update the display of the elapsed time since the last system boot up.

    ''' <summary>

    ''' Constructor - Enable the

    ''' Elapsed time timer control

    ''' </summary>

    ''' <remarks></remarks>

    Public Sub New()

 

        ' This call is required by the Windows Form Designer.

        InitializeComponent()

 

        ' Add any initialization after the InitializeComponent() call.

 

        ' start the timer

        timer1.Enabled = True 

    End Sub

Next up is form load event handler; in this section of code, a SelectQuery from System.Management is created and set to obtain the last boot up time from the operating system.  The query is executed and a ManagementDateTimeConverter is used convert the recovered value to a System.DateTime value.  That value is then used to set the boot time variable and to then display the start date and start time for the last system boot up.

    ''' <summary>

    ''' On form load, use a Management.Select query

    ''' to discover the last boot time and set

    ''' the boot time datetime variable to maintain

    ''' that value

    ''' </summary>

    ''' <param name="sender"></param>

    ''' <param name="e"></param>

    ''' <remarks></remarks>

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e

    As System.EventArgs) Handles MyBase.Load

 

        ' define a select query

        Dim query As _

        New SelectQuery("SELECT LastBootUpTime FROM Win32_OperatingSystem WHERE

        Primary='true'")

 

        ' create a new management object searcher and pass it

        ' the select query

        Dim searcher As New ManagementObjectSearcher(query)

 

        ' get the datetime value and set the local boot

        ' time variable to contain that value

        Dim mo As ManagementObject

 

        For Each mo In searcher.Get()

 

            dtBootTime = _

            ManagementDateTimeConverter.ToDateTime( _ 

            mo.Properties("LastBootUpTime").Value.ToString())

 

            ' display the start time and date

            txtDate.Text = dtBootTime.ToLongDateString()

            txtTime.Text = dtBootTime.ToLongTimeString()

 

        Next

 

        searcher = Nothing

        mo = Nothing 

    End Sub

Next up is the timer tick event handler; the timer is set to an interval of 1000 milliseconds and every time one second passes, the elapsed time is recalculated by setting the difference between the boot up time and the current time into a TimeSpan object.  The time span is then used to set the display of the hours, minutes, and seconds that have passed since the last system boot up.

    ''' <summary>

    ''' Update the display of the lapsed time

    ''' using the time span between the logged

    ''' boot time and now

    ''' </summary>

    ''' <param name="sender"></param>

    ''' <param name="e"></param>

    ''' <remarks></remarks>

    Private Sub timer1_Tick(ByVal sender As  _

                            System.Object, _

                            ByVal e As System.EventArgs) _

                            Handles timer1.Tick

 

        ' get the current difference betwee

        ' the last boot time and now using

        ' a timespace

        Dim ts As TimeSpan = DateTime.Now - dtBootTime

 

        ' display the hours, minutes, and seconds

        ' since the last boot time

        txtLapsedHours.Text = (ts.Hours).ToString()

        txtLapsedMinutes.Text = (ts.Minutes).ToString()

        txtLapsedSeconds.Text = (ts.Seconds).ToString()

 

    End Sub

 

The final code block is the button click event handler used to exit the application:

 

    ''' <summary>

    ''' Exit the application

    ''' </summary>

    ''' <param name="sender"></param>

    ''' <param name="e"></param>

    ''' <remarks></remarks>

    Private Sub btnExit_Click(ByVal sender As  _

                              System.Object, _

                              ByVal e As System.EventArgs) _

                              Handles btnExit.Click

 

        Application.Exit()

 

    End Sub 

End Class

Summary

This article is intended to describe an approach to obtaining the time since last system boot up through the use of the System.Management library.  The same approach may be used to extract other bits of information from the system in a similar fashion.  As an application, it is semi-useful to me, I keep something like this on my desktop; since I tend to work odd hours, I reboot my machine when I start a work session and use it to keep track of the exact amount of time that I have worked.


Similar Articles