我试图通过改变用户的形象(红色离线,绿色在线)来改变离线和在线之间的用户可用性。我正在使用此代码根据键盘和鼠标事件将用户状态从在线更改为离线:
public sealed class UserActivityMonitor
{
/// <summary>Determines the time of the last user activity (any mouse activity or key press).</summary>
/// <returns>The time of the last user activity.</returns>
public DateTime LastActivity => DateTime.Now - this.InactivityPeriod;
/// <summary>The amount of time for which the user has been inactive (no mouse activity or key press).</summary>
public TimeSpan InactivityPeriod
{
get
{
var lastInputInfo = new LastInputInfo();
lastInputInfo.CbSize = Marshal.SizeOf(lastInputInfo);
GetLastInputInfo(ref lastInputInfo);
uint elapsedMilliseconds = (uint) Environment.TickCount - lastInputInfo.DwTime;
elapsedMilliseconds = Math.Min(elapsedMilliseconds, int.MaxValue);
return TimeSpan.FromMilliseconds(elapsedMilliseconds);
}
}
public async Task WaitForInactivity(TimeSpan inactivityThreshold, TimeSpan checkInterval, CancellationToken cancel)
{
while (true)
{
await Task.Delay(checkInterval, cancel);
if (InactivityPeriod > inactivityThreshold)
return;
}
}
// ReSharper disable UnaccessedField.Local
/// <summary>Struct used by Windows API function GetLastInputInfo()</summary>
struct LastInputInfo
{
#pragma warning disable 649
public int CbSize;
public uint DwTime;
#pragma warning restore 649
}
// ReSharper restore UnaccessedField.Local
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetLastInputInfo(ref LastInputInfo plii);
}
然后我实现了在一段时间不活动后改变用户图片的东西。
readonly UserActivityMonitor _monitor = new UserActivityMonitor();
protected override async void OnLoad(EventArgs e)
{
base.OnLoad(e);
await _monitor.WaitForInactivity(TimeSpan.FromMinutes(10), TimeSpan.FromSeconds(5), CancellationToken.None);
//changepicture user from online to online
}
现在我想做同样的想法,在触发鼠标或键盘事件时再次将图像更改为在线用户。