How to change an image depending on keyboard and mouse activitiy?

78 Views Asked by At

I tried to change the user availability between offline & online by changing the image of the user (red offline, green online). I am using this code to change the user status from online to offline based on keyboard and mouse events:

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);
}

Then I implement something that changes the user picture after a certain period of inactivity.

    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
}

Now I want to do the same idea to change again the image to online user when mouse or keyboard event are triggered.

0

There are 0 best solutions below