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?<
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 );
}
}