views:

4537

answers:

4

I have to stop windows from going into sleep when my program is running.

And I don't only want to prevent the sleep-timer, I also want to cancel the sleep-event if I press the sleep-button or in any other way actively tell the computer to sleep. Therefore SetThreadExecutionState is not enough.

Or...I don't actually have to prevent the sleep completely, only delay it 5-10sec to allow my program to finish a task.

(I know that this is bad program behavior but it's only for personal use.)

A: 

How about waking it back up if it goes to sleep?

http://www.enterprisenetworksandservers.com/monthly/art.php?1049

Greg Dean
Not possible, i have to disable a wifi-device _before_ the computer goes to sleep. Otherwise the device will become unusable when i wake the computer up again. Intel is slow with win7 drivers :(
A: 

The same technique applies as for preventing the screensaver should be used. See http://stackoverflow.com/questions/463813/programmatically-prevent-windows-screensaver-from-starting.

Note that some security settings can override this (forcing computers to lock after a certain time is one).

Zooba
+1  A: 

It's different for Vista/Win2008 and XP, see this article:

http://msdn.microsoft.com/en-us/magazine/cc163386.aspx

markus
+5  A: 

I had a problem like this with a hardware device connected via usb. XP /Vista would sleep/hibernate right in the middle of ... Great you say, when it resumes it can just continue. If the hardware is still connected!!! Users have the habit of pulling cables out whenever they feel like it.

You need to handle XP and Vista

Under XP trap the WM_POWERBROADCAST and look for the PBT_APMQUERYSUSPEND wparam.

   // See if bit 1 is set, this means that you can send a deny while we are busy
   if (message.LParam & 0x1)
   {
      // send the deny message
      return BROADCAST_QUERY_DENY;
   } // if
   else
   {
      return TRUE;
   } // else

Under Vista use SetThreadExecutionState like this

// try this for vista, it will fail on XP
if (SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED | ES_AWAYMODE_REQUIRED) == NULL)
{
   // try XP variant as well just to make sure 
   SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED);
}  // if

and when you app has finished set it back to normal

// set state back to normal
SetThreadExecutionState(ES_CONTINUOUS);
Hmm, i was wrong, SetThreadExecutionState actually did work, just had to set the ES_AWAYMODE_REQUIRED also.The strange thing is that my monitor goes black but the system never fully goes to sleep.