How to check in C++ if the system is active?

前端 未结 6 1703
温柔的废话
温柔的废话 2021-02-09 10:16

I\'m writing code that need to run only when there is no human activity on the PC, like when the screensaver is running. Any suggestions on how to do this in c++ under windows?<

6条回答
  •  爱一瞬间的悲伤
    2021-02-09 10:53

    This is just a minor update to Niklas B. answer which is tested on Windows 8.1 and Windows 10.

    Description of changes is as follows:

    • LASTINPUTINFO has cbSize initialized

    • instead of checking SPI_GETSCREENSAVERACTIVE, SPI_GETSCREENSAVERRUNNING is checked

    • idle_time is calculated and compared with idle_milliseconds

    • user is notified only on change, check is executed every ~500ms

    • since windows can trigger event id 4803 immediately after 4802 one can determine that screensaver is still on with user idle_time, see the problem I had

    Additionally this only works if screensaver timer is smaller then screen power off timer!

    #define start

    #include 
    #include 
    
    // do something after 10 minutes of user inactivity
    static const unsigned int idle_milliseconds = 60*10*1000;
    
    int main() {
        LASTINPUTINFO last_input;
        // without setting cbSize GetLastError() returns the parameter is incorrect
        last_input.cbSize = sizeof(last_input);  
        BOOL screensaver_running;
    
        DWORD idle_time;
        bool screensaverOn = false;
    
        // main loop to check if user has been idle long enough
        for (;;) {
            if ( !GetLastInputInfo( &last_input )
              || !SystemParametersInfo( SPI_GETSCREENSAVERRUNNING, 0,  
                                   &screensaver_running, 0 ) )
            {
                std::cerr << "WinAPI failed!" << std::endl;
                return ERROR_FAILURE;
            }
    
            // calculate idle time
            idle_time = GetTickCount() - last_input.dwTime;
    
            if ( idle_time > this->user_idle_time && TRUE == screensaver_running )
            {
                if ( !screensaverOn )
                {
                    // screensaver is running
                    screensaverOn = true;
                    notify( true );
                }
            }
            else if ( idle_time < this->user_idle_time && screensaverOn )
            {
                // screensaver is not running
                screensaverOn = false;
                notify( false );
            }
            // wait 500ms before next loop
            Sleep( 500 );
        }
    }
    

提交回复
热议问题