Reputation: 21
I want an application that show message if user is inactive for certain minutes.
I have googled it and got solutions but it was hard to understand for me and I don't know how to use that code,
It would be appreciated if someone provides me some article that show step by step procedure to detect the inactivity of user and show the message in windows application c#.
Upvotes: 1
Views: 919
Reputation: 109822
This is quite easy to do using the Windows API call GetLastInputInfo()
, assuming you can do so. Here's a sample wrapper class for it:
public sealed class UserActivityMonitor
{
public UserActivityMonitor()
{
_lastInputInfo.CbSize = Marshal.SizeOf(_lastInputInfo);
}
/// <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
{
GetLastInputInfo(ref _lastInputInfo);
uint elapsedMilliseconds = (uint)Environment.TickCount - _lastInputInfo.DwTime;
elapsedMilliseconds = Math.Min(elapsedMilliseconds, int.MaxValue);
return TimeSpan.FromMilliseconds(elapsedMilliseconds);
}
}
/// <summary>Struct used by Windows API function GetLastInputInfo()</summary>
struct LastInputInfo
{
public int CbSize;
public uint DwTime;
}
[DllImport("user32.dll")]
[DefaultDllImportSearchPaths(DllImportSearchPath.System32)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool GetLastInputInfo(ref LastInputInfo plii);
LastInputInfo _lastInputInfo;
}
To use this, just create an instance of the class and check the InactivityPeriod
property periodically (for example, by using a Timer
).
Upvotes: 2