【发布时间】:2012-06-27 16:47:12
【问题描述】:
我想检查我的应用程序中的用户不活动。我做了一些研究并选择使用 GetLastInputInfo 和 Environment.TickCount 因为它看起来很简单。不幸的是,结果有点棘手。
GetLastInputInfo 返回一个 LASTINPUTINFO 结构,该结构具有最后一个“TickCount”值作为 DWORD(即 UInt32)。理论上,我想从 Environment.TickCount 中减去该值,这样我就知道了用户处于非活动状态的毫秒数。
Environment.TickCount 返回一个 Int32。当它们达到最大值时,两者都会环绕,这对于 Int32 和 UInt32 是不同的。处理这个我有点不舒服,特别是因为代码基本上无法测试(Environment.TickCount 会在 24.9 天后回绕,并且该功能应在此之前到期)。
这是我到目前为止所做的:
[DllImport("user32.dll")]
static extern bool GetLastInputInfo(out LastInputInfo plii);
struct LastInputInfo
{
public uint cbSize;
public uint dwTime;
}
//(...)
var lastInputInfo = new LastInputInfo();
lastInputInfo.cbSize = (uint)Marshal.SizeOf(lastInputInfo);
if (GetLastInputInfo(out lastInputInfo))
{
// The next line obviously will not work when either of the terms has wrapped around
var idleTime = Environment.TickCount - lastInputInfo.dwTime;
if (idleTime > mTimeOut)
{
// user is inactive!
}
}
是否有一种足够简单的方法来处理这两种环绕,或者我应该使用另一种方法来完全检测用户的不活动状态?也欢迎任何关于如何在不使用计算机 25 天的情况下进行测试的建议。
【问题讨论】:
-
请记住,这种方式只能检测到用户不活动时间以 ~50 天为模。
-
@HristoIliev 感谢您的提醒,但此功能的用例是 5 分钟到 1 小时不活动,所以这不是问题。