Skip to content

Instantly share code, notes, and snippets.

@ramonsmits
Created May 10, 2019 08:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ramonsmits/2f37c579e4e80927b57a5e5700e56b8b to your computer and use it in GitHub Desktop.
Save ramonsmits/2f37c579e4e80927b57a5e5700e56b8b to your computer and use it in GitHub Desktop.
Get Windows User idle time and correcting for 32 bit API uptime rollover
static class LastInputHelper
{
/// <remarks>http://www.pinvoke.net/default.aspx/user32.GetLastInputInfo</remarks>
[DllImport("User32.dll")]
static extern bool GetLastInputInfo(ref LASTINPUTINFO plii);
struct LASTINPUTINFO
{
public uint cbSize;
public uint dwTime;
}
public static TimeSpan GetIdleTime()
{
var plii = new LASTINPUTINFO { cbSize = (uint)Marshal.SizeOf(typeof(LASTINPUTINFO)) };
if (!GetLastInputInfo(ref plii)) return TimeSpan.Zero;
long up = (uint)Environment.TickCount;
long last = plii.dwTime;
var idle = up - last;
// if idle is negative, it means uptime rolled over and dwTime did not and we need to adjust
if (idle < 0) idle += uint.MaxValue;
return TimeSpan.FromMilliseconds(idle);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment