Jump to content

Recommended Posts

Posted (edited)

Screensaver, Sleep, Workstation Lock, and Power-Save Disabling


Since I see this question asked again and again, and the simple answer isn't always given (or at least, only half of it is), I'm posting this for reference.

To disable Power-saving, Workstation Locking, Screensavers, etc., all that's needed is a call to SetThreadExecutionState.  No need for timers, nor for emulating mouse or keyboard input.  Just make a call to that API once to disable any locking/sleeping/screensaverin'.  When you're done, make another call to it with the proper parameters (this part is important), and everything will be restored.

NOTE: The 'execution state' should really only matter while the program that made the call is running (its supposed to be per-application). Once it is terminated, the execution state should be restored. However, there have been some unusual reports regarding this, especially when it is called by more than one process.

The main functions in my module are _PowerKeepAlive() and  _PowerResetState().  One keeps everything 'awake', the other reenables the default state of Windows power settings (including screensavers and workstation locking).

The primary reason I've used this myself is for games that forget to call that API function, and after playing with the joystick for a while, a screensaver or lock-screen will pop up.  Using these functions will workaround that problem.

Also!: If you want to save and restore the current power-savings 'execution state', just pass the return value from _PowerKeepAlive() as the first argument to 'SetThreadExecutionState'.

 

Anyway, here's the main module I use (example use is below):

#include-once
; ===============================================================================================================================
; <_PowerKeepAlive.au3>
;
; Functions to prevent/disable sleep/power-savings modes (AND screensaver)
;
; Functions:
;    _PowerKeepAlive()
;    _PowerResetState()
;
; See also:
;    <_ScreenSaverFunctions.au3>    ; query, change, enable & disable screensaver.
;
; Author: Ascend4nt
; ===============================================================================================================================

; ==========================================================================================================================
; Func _PowerKeepAlive()
;
; Function to Prevent the Screensaver and Sleep/Power-savings modes from kicking in.
;    NOTE: Be sure to reset this state on exit!
;
; Returns:
;    Success: @error=0 & previous state as # (typically 0x80000000 [-2147483648])
;    Failure: @error set (returns 0x80000000, but thats just the normal state)
;        @error = 2 = DLLCall error. @extended = DLLCall error code (see AutoIt Help)
;
; Author: Ascend4nt
; ==========================================================================================================================

Func _PowerKeepAlive()
#cs
    ; Flags:
    ;    ES_SYSTEM_REQUIRED  (0x01) -> Resets system Idle timer
    ;    ES_DISPLAY_REQUIRED (0x02) -> Resets display Idle timer
    ;    ES_CONTINUOUS (0x80000000) -> Forces 'continuous mode' -> the above 2 will not need to continuously be reset
#ce
    Local $aRet=DllCall('kernel32.dll','long','SetThreadExecutionState','long',0x80000003)
    If @error Then Return SetError(2,@error,0x80000000)
    Return $aRet[0]    ; Previous state (typically 0x80000000 [-2147483648])
EndFunc

; ==========================================================================================================================
; Func _PowerResetState()
;
; Function to Reset the Screensaver and Sleep/Power-savings modes to defaults.
;    NOTE: The timer is reset on each call to this!
;
; Returns:
;    Success: @error=0 & previous state as #
;    Failure: @error set (returns 0x80000000, but thats just the normal state)
;        @error = 2 = DLLCall error. @extended = DLLCall error code (see AutoIt Help)
;
; Author: Ascend4nt
; ==========================================================================================================================

Func _PowerResetState()
    ; Flag:    ES_CONTINUOUS (0x80000000) -> (default) -> used alone, it resets timers & allows regular sleep/power-savings mode
    Local $aRet=DllCall('kernel32.dll','long','SetThreadExecutionState','long',0x80000000)
    If @error Then Return SetError(2,@error,0x80000000)
    Return $aRet[0]    ; Previous state
EndFunc

Example usage:

#NoTrayIcon
#include "_PowerKeepAlive.au3"

; Singleton code:
If WinExists("SA_0bc53fe0-59c2-11e2-bcfd-0800200c9a66_SA") Then Exit
AutoItWinSetTitle("SA_0bc53fe0-59c2-11e2-bcfd-0800200c9a66_SA")

Opt("TrayOnEventMode", 0)
Opt("TrayMenuMode", 1+2)
TraySetClick(8+1)

Local $iTrayExit = TrayCreateItem("Exit + Reenable Sleep")

; Disable screensaver, power-save, etc
_PowerKeepAlive()
; Be sure to register this to reenable power-saving, screensaver, etc
OnAutoItExitRegister("_PowerResetState")

; Now we're ready to accept messages
TraySetState()

While TrayGetMsg() <> $iTrayExit
    ; No need for sleep
WEnd

_PowerKeepAlive.au3

Edited by Ascend4nt

My contributions:

  Reveal hidden contents

Performance Counters in Windows - Measure CPU, Disk, Network etc Performance | Network Interface Info, Statistics, and Traffic | CPU Multi-Processor Usage w/o Performance Counters | Disk and Device Read/Write Statistics | Atom Table Functions | Process, Thread, & DLL Functions UDFsProcess CPU Usage Trackers | PE File Overlay Extraction | A3X Script Extract | File + Process Imports/Exports Information | Windows Desktop Dimmer Shade | Spotlight + Focus GUI - Highlight and Dim for Eyestrain Relief | CrossHairs (FullScreen)Rubber-Band Boxes using GUI's (_GUIBox) | GUI Fun! | IE Embedded Control Versioning (use IE9+ and HTML5 in a GUI) | Magnifier (Vista+) Functions UDF | _DLLStructDisplay (Debug!) | _EnumChildWindows (controls etc) | _FileFindEx | _ClipGetHTML | _ClipPutHTML + ClipPutHyperlink | _FileGetShortcutEx | _FilePropertiesDialog | I/O Port Functions | File(s) Drag & Drop | _RunWithReducedPrivileges | _ShellExecuteWithReducedPrivileges | _WinAPI_GetSystemInfo | dotNETGetVersions | Drive(s) Power Status | _WinGetDesktopHandle | _StringParseParameters | Screensaver, Sleep, Desktop Lock Disable | Full-Screen Crash Recovery

Wrappers/Modifications of others' contributions:

_DOSWildcardsToPCRegEx (original code: RobSaunder's) | WinGetAltTabWinList (original: Authenticity)

UDF's added support/programming to:

_ExplorerWinGetSelectedItems | MIDIEx UDF (original code: eynstyne)

(All personal code/wrappers centrally located at Ascend4nt's AutoIT Code)

Posted

Interesting. Hands up I've always said do it with a timer, so good to know I can point them to this in the future.

UDF List:

  Reveal hidden contents

Updated: 22/04/2018

Posted

Nice, never seen that one before.

Not sure I get this though

  Quote

ES_USER_PRESENT

0x00000004

This value is not supported. If ES_USER_PRESENT is combined with other esFlags values, the call will fail and none of the specified states will be set.

Windows Server 2003 and Windows XP:  Informs the system that a user is present and resets the display and system idle timers. ES_USER_PRESENT must be called with ES_CONTINUOUS.

Perhaps I'm not reading it right.

AutoIt Absolute Beginners    Require a serial    Pause Script    Video Tutorials by Morthawt   ipify 

Monkey's are, like, natures humans.

Posted (edited)

JohnOne, don't use ES_USER_PRESENT.  It's not required if you use ES_CONTINUOUS; rather, it's the other way around - IF you use ES_USER_PRESENT, than you must use ES_CONTINUOUS.  But as it's no longer supported, and I don't see a good use for it - ignore it :)

Edited by Ascend4nt

My contributions:

  Reveal hidden contents

Performance Counters in Windows - Measure CPU, Disk, Network etc Performance | Network Interface Info, Statistics, and Traffic | CPU Multi-Processor Usage w/o Performance Counters | Disk and Device Read/Write Statistics | Atom Table Functions | Process, Thread, & DLL Functions UDFsProcess CPU Usage Trackers | PE File Overlay Extraction | A3X Script Extract | File + Process Imports/Exports Information | Windows Desktop Dimmer Shade | Spotlight + Focus GUI - Highlight and Dim for Eyestrain Relief | CrossHairs (FullScreen)Rubber-Band Boxes using GUI's (_GUIBox) | GUI Fun! | IE Embedded Control Versioning (use IE9+ and HTML5 in a GUI) | Magnifier (Vista+) Functions UDF | _DLLStructDisplay (Debug!) | _EnumChildWindows (controls etc) | _FileFindEx | _ClipGetHTML | _ClipPutHTML + ClipPutHyperlink | _FileGetShortcutEx | _FilePropertiesDialog | I/O Port Functions | File(s) Drag & Drop | _RunWithReducedPrivileges | _ShellExecuteWithReducedPrivileges | _WinAPI_GetSystemInfo | dotNETGetVersions | Drive(s) Power Status | _WinGetDesktopHandle | _StringParseParameters | Screensaver, Sleep, Desktop Lock Disable | Full-Screen Crash Recovery

Wrappers/Modifications of others' contributions:

_DOSWildcardsToPCRegEx (original code: RobSaunder's) | WinGetAltTabWinList (original: Authenticity)

UDF's added support/programming to:

_ExplorerWinGetSelectedItems | MIDIEx UDF (original code: eynstyne)

(All personal code/wrappers centrally located at Ascend4nt's AutoIT Code)

  • 4 months later...
Posted
Very helpful.
Thanks for this script.
 
Best regards.
mlipok

Signature beginning:
Please remember: "AutoIt"..... *  Wondering who uses AutoIt and what it can be used for ? * Forum Rules *
ADO.au3 UDF * POP3.au3 UDF * XML.au3 UDF * IE on Windows 11 * How to ask ChatGPT for AutoIt Codefor other useful stuff click the following button:

  Reveal hidden contents

Signature last update: 2023-04-24

  • 3 months later...
Posted (edited)

I know thread this is about a year old but wondered....

Will the default settings be restored on a logoff/logon or a system restart?

Edited by NewPlaza
  • 2 years later...
Posted (edited)
  On 7/6/2013 at 10:28 PM, Ascend4nt said:

Also!: If you want to save and restore the current power-savings 'execution state', just pass the return value from _PowerKeepAlive() as the first argument to 'SetThreadExecutionState'.

Expand  
; save the current power-savings 'execution state'
Global $Power =_PowerKeepAlive()
; Be sure to register this to reenable power-saving, screensaver, etc
OnAutoItExitRegister("_PowerResetState")

; saves the current power-savings 'execution state'
Func _PowerKeepAlive()
    Local $aRet=DllCall('kernel32.dll','long','SetThreadExecutionState','long',0x80000003)
    If @error Then Return SetError(2,@error,0x80000000)
    MsgBox(0,'',$aRet[0])
    Return $aRet[0] ; Previous state (typically 0x80000000 [-2147483648])
EndFunc

; restore the previous power-savings 'execution state'
Func _PowerResetState()
    ; Flag: ES_CONTINUOUS (0x80000000) -> (default) -> used alone, it resets timers & allows regular sleep/power-savings mode
    Local $aRet=DllCall('kernel32.dll','long','SetThreadExecutionState','long',$Power)
    If @error Then Return SetError(2,@error,0x80000000)
    MsgBox(0,'',$aRet[0])
    Return $aRet[0] ; Previous state
EndFunc


For $power I'd get "-2147483648" @ $aRet[0]    
 when the _PowerResetState() kicks in, it will return "-2147483645" @ $aRet[0] which is differed from the (saved) $power value
    
so just to stay sure, will this still work out correctly ?

Thanks

Edited by Deye

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...