Introduction
This article described code for calculating for how long a system has been idle. This is useful to do background work etc. There might be other similar articles on the web and/or CodepPoject; if you find a better way, please do let me know. The attached sample is a simple WinForms application to demonstrate the code.
Background
I was browsing the web and encountered a couple of articles on how to calculate idle time, but they were doing it using system wide hooks. We don't want to install hooks, do we? Especially for a simple task like calculating system idle time. So, the result is this article.
Using the code
The code is very simple, just a couple of Windows API function calls.
Dim idleStruct As LASTINPUTINFO
idleStruct.cbSize = Marshal.SizeOf(idleStruct)
If GetLastInputInfo(idleStruct) Then
Dim sysIdleTime As Integer = GetTickCount() - idleStruct.dwTime
Dim totalTime As New TimeSpan(sysIdleTime * 10000)
End If
All we need to do is create an object of the LASTINPUTINFO
structure. Before passing it as a parameter, set its size using the Marshal.SizeOf
method. The function GetLastInputInfo
is used to populate the dwTime
property of the LASTINPUTINFO
structure. If the function is successful, it returns true
; otherwise false
. Once the dwTime
is populated, we call another function GetTickCount
; what this does is it calculates the time since the Windows session was started. And, the API declarations are as follows:
<StructLayout(LayoutKind.Sequential)> _
Public Structure LASTINPUTINFO
Public cbSize As Integer
Public dwTime As Integer
End Structure
Public Declare Function GetLastInputInfo Lib "User32.dll" _
(ByRef lii As LASTINPUTINFO) As Boolean
Public Declare Function GetTickCount Lib "kernel32" _
Alias "GetTickCount" () As Integer
Conclusion
I hope this article helps my fellow developers. If you like this article, please do vote for it. And, if you find a bug or improvement, do let me know.