我正在写需要检测一次用户与他们的机器进行交互,以确定它们是否空闲的小托盘应用。
有没有什么办法来检索用户最后把他们的鼠标,投中关键或与他们的机器任何方式交互的时间?
我想很明显的Windows跟踪该确定时显示屏幕保护程序或关机等,所以我假设有检索这个自己一个Windows API?
我正在写需要检测一次用户与他们的机器进行交互,以确定它们是否空闲的小托盘应用。
有没有什么办法来检索用户最后把他们的鼠标,投中关键或与他们的机器任何方式交互的时间?
我想很明显的Windows跟踪该确定时显示屏幕保护程序或关机等,所以我假设有检索这个自己一个Windows API?
GetLastInputInfo 。 在记录PInvoke.net 。
包括下面的命名空间
using System;
using System.Runtime.InteropServices;
然后包括以下
internal struct LASTINPUTINFO
{
public uint cbSize;
public uint dwTime;
}
/// <summary>
/// Helps to find the idle time, (in milliseconds) spent since the last user input
/// </summary>
public class IdleTimeFinder
{
[DllImport("User32.dll")]
private static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);
[DllImport("Kernel32.dll")]
private static extern uint GetLastError();
public static uint GetIdleTime()
{
LASTINPUTINFO lastInPut = new LASTINPUTINFO();
lastInPut.cbSize = (uint)System.Runtime.InteropServices.Marshal.SizeOf(lastInPut);
GetLastInputInfo(ref lastInPut);
return ((uint)Environment.TickCount - lastInPut.dwTime);
}
/// <summary>
/// Get the Last input time in milliseconds
/// </summary>
/// <returns></returns>
public static long GetLastInputTime()
{
LASTINPUTINFO lastInPut = new LASTINPUTINFO();
lastInPut.cbSize = (uint)System.Runtime.InteropServices.Marshal.SizeOf(lastInPut);
if (!GetLastInputInfo(ref lastInPut))
{
throw new Exception(GetLastError().ToString());
}
return lastInPut.dwTime;
}
}
到计时单位计数转换成时间,你可以使用
TimeSpan timespent = TimeSpan.FromMilliseconds(ticks);
注意。 这个程序使用的术语是计时单位计数,但值以毫秒为单位,并是如此不一样的蜱。
从上Environment.TickCount MSDN文章
获取自系统启动后所经过的毫秒数。
码:
using System;
using System.Runtime.InteropServices;
public static int IdleTime() //In seconds
{
LASTINPUTINFO lastinputinfo = new LASTINPUTINFO();
lastinputinfo.cbSize = Marshal.SizeOf(lastinputinfo);
GetLastInputInfo(ref lastinputinfo);
return (((Environment.TickCount & int.MaxValue) - (lastinputinfo.dwTime & int.MaxValue)) & int.MaxValue) / 1000;
}