Prevent Windows 7 from sleep + power button hook

I'm used to not shutdown Windows but to sleeping it. I set up power button (PB) action to do it. When I want to shutdown I must go to start -> Shutdown. That's OK.

Now I think of a mechanism that will be hooked up to a PB. Should be started after I press PB but before OS will go to sleep. Something that will check few conditions (i.e. running backup, running AV scan, ...) and if true (something is running) prevent go to sleep.

Optionally: It would be nice to start the same "mechanism" before restart and shutdown (invoked not only from Start menu, but also by other software (i.e. installers) but with option to allow some sources (i.e. UPS software)

Generally: How to run something after PowerButton but before Sleeping. How to code (C#.NET, vbs, batch (preferred)) sleep prevention (cancellation).


Solution 1:

Sometimes it may happen that you shut down your Windows 7 unintentionally. Windows 7 will then automatically shut down all your programs and and you might loose changes. But you can prevent this from happening. Here is how it is done:

Turn Off Auto Closing of Programs at Shutdown in Windows 7

Windows 7 Professional:

  • Press the Windows button and type in the search gpedit.msc. Right click on it and run with Administrator rights. Now go to Computer ConfigurationAdministrative TemplatesSystemShutdown Options. In the right hand side pane, you will find a value Turn off automatic termination of applications that block or cancel shutdown. Double click on it and choose Enabled. Click OK to save the settings and close the dialog.

gpedit.msc Turn Auto Closing of Programs

Windows 7 Home Edition:

  • For this version of Windows 7 you will have to hack the registry or just download turnoff_autoclose_policy_win7.zip. Just extract it on your desktop and double click on turnoff_autoclose_policy_win7.reg and click 'YES'. This will automatically add a New → DWORD (32-bit Value) to the registry key HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\System.

Powercfg Command-Line Options

  • In the command line you can type POWERCFG -REQUESTSOVERRIDE PROCESS name_of_the_process Display System and this will prevent Windows 7 to go to sleep while a certain process is running. I never used it so you must read the manual here.

    Usage: POWERCFG -REQUESTSOVERRIDE <CALLER_TYPE> <NAME> <REQUEST> Specifies one of the following caller type: PROCESS, SERVICE, DRIVER. This is obtained by calling the POWERCFG -REQUESTS command. Specifies the caller name. This is the name returned from calling POWERCFG -REQUESTS command. Specifies one or more of the following Power. Request Types: Display, System, Awaymode.

    Example: POWERCFG -REQUESTSOVERRIDE PROCESS wmplayer.exe Display System

    To remove the power request override, use the -REQUESTSOVERRIDE option, but do not specify any type of override (System, Display, AwayMode) as in the following example: POWERCFG -REQUESTSOVERRIDE PROCESS wmplayer.exe