如何检查用户是否处于非活动状态?我有这个:
class UserActivity : IMessageFilter
{
private double afk_time = 0.1;//minutes
private DateTime last_activity = DateTime.Now;
public static bool inactive = false;
private int WM_LBUTTONDOWN = 0x0201;
private int WM_MBUTTONDOWN = 0x0207;
private int WM_RBUTTONDOWN = 0x0204;
private int WM_MOUSEWHEEL = 0x020A;
private int WM_MOUSEMOVE = 0x0200;
private int WM_KEYDOWN = 0x0100;
public bool PreFilterMessage(ref Message m)
{
if (m.Msg == WM_LBUTTONDOWN || m.Msg == WM_MBUTTONDOWN || m.Msg == WM_RBUTTONDOWN || m.Msg == WM_MOUSEWHEEL || m.Msg == WM_MOUSEMOVE || m.Msg == WM_KEYDOWN)
{
this.last_activity = DateTime.Now;
inactive = false;
}
if (DateTime.Now.AddMinutes(-afk_time) > last_activity)
inactive = true;
return false;
}
}
但我必须在程序中运行它.cs
Application.AddMessageFilter(new UserActivity());
我该怎么做,我可以自己运行用户不活动的检查。我会选中一些复选框,它将开始检查。
我想检查全球用户活动 - 在所有系统中,而不仅仅是在应用程序中。
我不希望不必要地使用 CPU。还是我应该使用其他解决方案?
我找到了这个,它工作得很好!因此,如果另一个人有问题,这里是解决方案:
[StructLayout(LayoutKind.Sequential)]
public struct LASTINPUTINFO
{
public uint cbSize;
public uint dwTime;
}
[DllImport("user32.dll")]
static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);
public static TimeSpan? GetInactiveTime()
{
LASTINPUTINFO info = new LASTINPUTINFO();
info.cbSize = (uint)Marshal.SizeOf(info);
if (GetLastInputInfo(ref info))
return TimeSpan.FromMilliseconds(Environment.TickCount - info.dwTime);
else
return null;
}
我试图在以前的答案上建立一个类基础,我已经测试了它并且它工作正常。它是异步的,但我没有使用异步键。如果有人发现一些问题或改善,欢迎。
public class User
{
[StructLayout(LayoutKind.Sequential)]
public struct LASTINPUTINFO
{
public uint cbSize;
public uint dwTime;
}
[DllImport("user32.dll")]
static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);
public static TimeSpan? GetInactiveTime()
{
LASTINPUTINFO info = new LASTINPUTINFO();
info.cbSize = (uint)Marshal.SizeOf(info);
if (GetLastInputInfo(ref info))
return TimeSpan.FromMilliseconds(Environment.TickCount - info.dwTime);
else
return null;
}
private TimeSpan? LastTime;
private DispatcherTimer timer = new DispatcherTimer();
public void RequestUserActivity()
{
LastTime = GetInactiveTime();
timer.Interval = TimeSpan.FromMilliseconds(500);
timer.Tick += timer_Tick;
timer.Start();
}
void timer_Tick(object sender, EventArgs e)
{
TimeSpan? tmpTime = GetInactiveTime();
if (LastTime.HasValue && tmpTime.HasValue && tmpTime < LastTime)
{
timer.Stop();
UserAtivited(this, new EventArgs());
}
else if (!LastTime.HasValue || !tmpTime.HasValue)
{
timer.Stop();
throw new Exception();
}
}
public event EventHandler UserAtivited;
}
现在,在您的窗口中创建一个新的User实例,注册到UserActivated event并laugth RequestUserActivity()。我专家它会有所帮助。
请不要关心我糟糕的英语。我是讲法语的人。