I use a Windows API call to GetLastInputInfo to determine if the system is idle. This works in pretty much any scenario - except when Windows is set to bypass the username/password and login automatically.
In this case, querying GetLastInputInfo always returns 0. In normal conditions, it would return the system tick count when the last input occurred.
Does anyone know why? Or does anyone know an alternate method to determine if a windows session is idle?
This is how the code is written to detect the current system idle time. The detection occurs on a timer and regardless of how long the timer runs, GetLastInputInfo will always return 0 while windows is set to "auto login".
long lastInputTicks = 0;
long idleTicks = 0;
LASTINPUTINFO lastInputInfo = new LASTINPUTINFO();
lastInputInfo.cbSize = (uint)Marshal.SizeOf(lastInputInfo);
lastInputInfo.dwTime = 0;
if (GetLastInputInfo(ref lastInputInfo)) {
lastInputTicks = lastInputInfo.dwTime;
var systemUptime = GetTickCount();
idleTicks = systemUptime - lastInputTicks;
}
return new TimeSpan(0, 0, (int)(idleTicks / 1000));
Thanks
I've confirmed that this only happens because the code runs in a service.
To clarify: Under a normal scenario where auto-login is not being used, the user logs in at the console and the above code -- even if running as a service -- will return the proper user inactivity time.
However, if auto-login is turned on, then the windows session appears to not run as a typical console session, and is therefore NOT tracked. This applies only when the code is ran from a service and not from the "user space" - it works great in all cases if running from a user space.
That said, I'd really love to find a solution that works from a service in every scenario.
It returns 0 seconds when GetLastInput() returns FALSE. Which is obviously incorrect. You cannot use code like this in a service, it doesn't have a way to retrieve user input. If GetLastInput() ever returns FALSE (likely with auto-login) then it will return FALSE forever.
Having services be aware of user sessions is a lost cause in Windows, a service runs in its own session and doesn't need a user to be logged-in. Which is the major reason to use a service in the first place. Instead of a program that's started with, say, a shortcut in the Startup folder. This code might have worked by accident in XP but it definitely won't work in Vista and Windows 7. Google "session 0 isolation" for more details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With