如何根据键盘和鼠标的活动来更改图像?

时间:2018-12-19 09:05:45

标签: c# winforms mouse keyboard-input user-activity

我试图通过更改用户的形象(红色的离线,绿色的在线)来更改离线和在线之间的用户可用性。 我正在使用以下代码根据键盘和鼠标事件将用户状态从在线更改为离线:

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
}

现在,我想做同样的想法在触发鼠标或键盘事件时再次将图像更改为在线用户。

0 个答案:

没有答案