简体   繁体   中英

How to detect system idle in windows service?

GetLastInputInfo can work well on application but not a service.

GetLastInputInfo will always return LASTINPUTINFO.dwTime=0 since it is running on Session 0.

How can I achieve detecting the system is idle or not in Windows Service?

Your service can enumerate the active sessions via WTSEnumerateSessions() , querying each session for its WTSSessionInfo/Ex via WTSQuerySessionInformation() . That will give you each session's LastInputTime (amongst other things).

PWTS_SESSION_INFO sessions = NULL;
DWORD count = 0;

if (!WTSEnumerateSessions(WTS_CURRENT_SERVER_HANDLE, 0, 1, &sessions, &count))
{
    DWORD errCode = GetLastError();
    ...
}
else
{
    for (DWORD i = 0; i < count; ++i)
    {
        PWTSINFO info = NULL;
        DWORD size = 0;

        if (!WTSQuerySessionInformation(WTS_CURRENT_SERVER_HANDLE, sessions[i].SessionId, WTSSessionInfo, (LPWSTR*)&info, &size))
        {
            DWORD errCode = GetLastError();
            ...
        }
        else
        {
            // use info->LastInputTime as needed...
            WTSFreeMemory(info);
        }
    }
    WTSFreeMemory(sessions);
}

If you are interested only in the session that is connected to the local machine's physical screen/keyboard/mouse, you can use WTSGetActiveConsoleSessionId() instead of WTSEnumerateSessions() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM