Stay awake!

From time to time it appears that I need to keep my PC running and prevent it from going to sleep. There are a couple of places where screen timeouts and standby/sleep options can be configured: Engery options, screen saver, system idle timeout, just to name the most common ones. To get rid of it you need to figure out, which of those values are responsible for your screen timeout. It becomes even more difficult, if those options are set by Group Policy.

The following script revokes the system sleep and powersave rules by setting its own thread to an execution state, which requires the screen and the system. We already know this from games or video players. As long as the script is running, the system is not allowed to go to sleep or turn off your screen. You don’t need administrative rights to run it. Simply run it as user.

Function SetExecutionState
{
    [CmdletBinding()]
    [Alias()]
    [OutputType([int])]
    Param
    (
        [ValidateSet("SystemRequired","Continuous")]
        [string] $executionState
    )

    $memberDefinition='[DllImport("kernel32.dll", CharSet = CharSet.Auto,SetLastError = true)] public static extern void SetThreadExecutionState(uint esFlags);'

    $winNative = Add-Type -memberDefinition $memberDefinition -name System -namespace Win32 -passThru 
    $ES_CONTINUOUS = [uint32]"0x80000000"
    $ES_AWAYMODE_REQUIRED = [uint32]"0x00000040"
    $ES_DISPLAY_REQUIRED = [uint32]"0x00000002"
    $ES_SYSTEM_REQUIRED = [uint32]"0x00000001"

	$bitFlags = ""
	Switch ($executionState)
    {
		"Continuous" {$bitFlags = $ES_CONTINUOUS}
		"SystemRequired" {$bitFlags = $ES_CONTINUOUS -bor $ES_SYSTEM_REQUIRED -bor $ES_DISPLAY_REQUIRED}
		Default {$bitFlags = $ES_CONTINUOUS}
    }

    $winNative::SetThreadExecutionState($bitFlags)
}

$ret = SetExecutionState -executionState SystemRequired
Read-Host “Press Return to terminate...”
$ret = SetExecutionState -executionState Continuous

For your convenience I also coded a little executable that sits in the notification area and does the same thing as the powershell script above. It nearly requires no system resources because it’s basically just an idle application that flags its executing thread with SYSTEM_REQUIRED and DISPLAY_REQUIRED. That means, as long as it is running, the system is not allowed to go to sleep or turn off the display. It is just a single EXE file based on .NET 4.0 and there are no admin privileges required for execution.

Simply download the utility from the link below and put it in a directory of your choice (a subfolder within %localappdata% would be a good choice). You can also run StayAwake.exe from command line to specify following options:

  • -tray: Starts StayAwake minimized in the notification area
  • -autostart: Creates a shortcut in the user’s Startup folder
  • -timeout <seconds>: Automatically stops StayAwake after the number of specified seconds


Posted

in

by

Tags:

Comments

Leave a Reply