Created
May 10, 2019 08:49
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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