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

前端 未结 6 1700
温柔的废话
温柔的废话 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:57

    You can use GetLastInputInfo to check how long the user has been idle (not moved around the mouse or typed something on the keyboard) and SystemParametersInfo to check if a screensaver is active.

    Example

    #define WINDOWS_LEAN_AND_MEAN
    #include 
    #include 
    
    // do something after 10 minutes of user inactivity
    static const unsigned int idle_milliseconds = 60*10*1000;
    // wait at least an hour between two runs
    static const unsigned int interval = 60*60*1000;
    
    int main() {
        LASTINPUTINFO last_input;
        BOOL screensaver_active;
    
        // main loop to check if user has been idle long enough
        for (;;) {
            if ( !GetLastInputInfo(&last_input)
              || !SystemParametersInfo(SPI_GETSCREENSAVERACTIVE, 0,  
                                       &screensaver_active, 0))
            {
                std::cerr << "WinAPI failed!" << std::endl;
                return ERROR_FAILURE;
            }
    
            if (last_input.dwTime < idle_milliseconds && !screensaver_active) {
                // user hasn't been idle for long enough
                // AND no screensaver is running
                Sleep(1000);
                continue;
            }
    
            // user has been idle at least 10 minutes
            do_something();
            // done. Wait before doing the next loop.
            Sleep(interval);
        }
    }
    

    Note that I wrote that code on a Linux machine, so I couldn't test it.

提交回复
热议问题