Visual Basic.NET 7.x (2002/03)Visual Basic 10Visual Basic 9 (2008)Visual Basic 8 (2005).NET 1.0Visual Studio 2008.NET 1.1.NET 3.0.NET4.NET 2.0.NET 3.5初学者中级开发Visual Studio.NETVisual Basic
无需挂钩即可计算系统空闲时间






4.71/5 (6投票s)
本文档演示如何在不安装任何系统范围内的键盘/鼠标钩子的情况下计算系统空闲时间。
引言
本文描述了计算系统空闲时间的代码。这对于执行后台工作等任务很有用。网上和/或CodepPoject上可能还有其他类似的文档;如果您找到更好的方法,请告诉我。 附带的示例是一个简单的WinForms应用程序,用于演示该代码。
背景
我在浏览网页时遇到了一些关于如何计算空闲时间的文章,但它们都是使用系统范围内的钩子来实现的。我们不想安装钩子,不是吗?特别是对于像计算系统空闲时间这样简单的任务。因此,就有了这篇文章。
使用代码
代码非常简单,只需要调用几个Windows API函数。
Dim idleStruct As LASTINPUTINFO
idleStruct.cbSize = Marshal.SizeOf(idleStruct)
'check if we are able to calculate time.
If GetLastInputInfo(idleStruct) Then
Dim sysIdleTime As Integer = GetTickCount() - idleStruct.dwTime
Dim totalTime As New TimeSpan(sysIdleTime * 10000)
End If
我们所需要做的就是创建一个LASTINPUTINFO
结构的实例。在将其作为参数传递之前,使用Marshal.SizeOf
方法设置其大小。GetLastInputInfo
函数用于填充LASTINPUTINFO
结构的dwTime
属性。如果函数成功,则返回true
;否则返回false
。 一旦填充了dwTime
,我们调用另一个函数GetTickCount
;它的作用是计算Windows会话启动后的时间。API声明如下:
''' <summary>
''' Structure for last input infomation.
''' </summary>
''' <remarks>More info about
''' it http://msdn.microsoft.com/en-us/library/ms646272(VS.85).aspx
''' </remarks>
<StructLayout(LayoutKind.Sequential)> _
Public Structure LASTINPUTINFO
Public cbSize As Integer
Public dwTime As Integer
End Structure
''' <summary>
''' Function to get the last input value.
''' </summary>
''' <param name="lii"></param>
''' <returns>Returns true on sucess and false on failure.</returns>
''' <remarks>More info about it http://msdn.microsoft.com/
''' en-us/library/ms646302(VS.85).aspx</remarks>
Public Declare Function GetLastInputInfo Lib "User32.dll" _
(ByRef lii As LASTINPUTINFO) As Boolean
''' <summary>
''' Get the time since windows started.
''' </summary>
''' <returns></returns>
''' <remarks>http://msdn.microsoft.com/en-us/library/ms724408(VS.85).aspx</remarks>
Public Declare Function GetTickCount Lib "kernel32" _
Alias "GetTickCount" () As Integer
结论
希望这篇文章对我的开发者同仁有所帮助。如果您喜欢这篇文章,请投票支持它。如果您发现任何错误或改进之处,请告诉我。