I have an application running on a Windows 10 machine. I would like to be able to determine if the currently logged in user is idle/away from the PC without having locked the screen. The idea is that since my application is showing sensitive data I would like to have an auto-logout in my application if the user is idle for some time. The idle time should however not be the idle time from my application, but from the whole Windows session. If the user does not use my application but is active with another app (using mouse/keyboard) this should not count as being idle. So I guess my question is: Is there a way to determine if the user is idle and for how long?
Asked
Active
Viewed 2,175 times
1
-
https://stackoverflow.com/questions/1442246/how-to-get-the-last-windows-active-time-by-windows-api – Hans Passant Apr 06 '22 at 00:03
1 Answers
1
To determine how long a user has been idle, the system provides the GetLastInputInfo
API call. To get notified when a user has been idle for a specified amount of time an application would usually do the following:
- Set up a timer with the specified timeout (
SetTimer
) - When the timer expires calculate the difference between
GetTickCount
andGetLastInputInfo
(dwCurrent - dwLastInput
reliably calculates the elapsed time since the last user input, even whenGetTickCount
wraps around to 0; unsigned integer overflow is well defined in C and C++) - If the difference is smaller than the specified timeout, start over from 1. with the remainder of the timeout
- Otherwise the timeout has elapsed without user input, so do whatever your program needs to do after a user has been idle for the specified amount of time

IInspectable
- 46,945
- 8
- 85
- 181
-
There's an issue with this method: sometimes the user may have not interacted via input but is doing an activity that sets the thread execution state to ES_SYSTEM_REQUIRED (which prevents locking/sleep). Such is the case for watching a video in a browser. In these cases there is no input, but the computer is not technically idle, this method would still interpret it as idle and give false positives. – Joacopaz Jul 27 '23 at 08:43
-
@Joacopaz No, this function will not produce false positives. It triggers when the system hasn't received input for a set amount of time. And that's all it does. The "false positive" is what **you** make out of this information. – IInspectable Aug 06 '23 at 16:15