Ascend4nt

Screensaver, Sleep, Lock and Power-Save Disabling

8 posts in this topic

#1 ·  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
1 person likes this

Share this post


Link to post
Share on other sites



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.


_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 04/09/2015

Share this post


Link to post
Share on other sites

Nice, never seen that one before.

Not sure I get this though

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.

Share this post


Link to post
Share on other sites

#4 ·  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

Share this post


Link to post
Share on other sites
Very helpful.
Thanks for this script.
 
Best regards.
mlipok

Signature beginning:   Wondering who uses AutoIT and what it can be used for ?
* GHAPI UDF - modest begining - comunication with GitHub REST API *
ADO.au3 UDF     POP3.au3 UDF     XML.au3 UDF    How to use IE.au3  UDF with  AutoIt v3.3.14.x  for other useful stuff click the following button

Spoiler

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST API *

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 - BETA * ADO.au3 UDF SMTP Mailer UDF *

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Best coding practices * 

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * 

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2017-06-04

Share this post


Link to post
Share on other sites

#7 ·  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

Share this post


Link to post
Share on other sites

#8 ·  Posted (edited)

On 7/7/2013 at 1:28 AM, 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'.

; 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

Share this post


Link to post
Share on other sites

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

  • Similar Content

    • thoms
      By thoms
      Hello Forum,
      As said in the title, I'm searching a way to disable all tabstops in a GUI. My GUI includes 15 buttons and 3 edit controls.
      My questions:
      - is there a way to disable all tabstops at a time
      - is there a way to list all controls of a GUI and then disable tabstops one by one
      - or should I use the following line after each button creation:
      _WinAPI_SetWindowLong(GUICtrlGetHandle(-1), $GWL_STYLE, BitAND(_WinAPI_GetWindowLong(GUICtrlGetHandle(-1), $GWL_STYLE), BitNOT($WS_TABSTOP))) Thanks in advance for your valuable help!
      Thoms
      Edit: or maybe disable TAB key? I don't remember how to do!
    • irishsurfer22
      By irishsurfer22
      Hi,
      I'm trying to automate the process of configuring the three McAfee settings seen in the image I've attached (Host IPS, Network IPS and Firewall).  Clicking one of them toggles the setting and closes the menu.  I want them all OFF.  This script will be used on different computers so the settings might be have different initial setups.
      This is my first time using AutoIt and I have very limited coding experience--mostly MATLAB.  Please excuse any lack of knowledge or terminology. 
      So far my code is able to
      1. Find the visible McAfee icon in the system tray. 
      2. Click the icon.
      3. Send "Q" to open up the Quick Settings menu.
      4. Toggle settings blindly using keystrokes.
      The problem I'm having is I don't know how to "read" the status of the setting before toggling it.  This means I might be switching it from Off to On by mistake,
      when I should really just leave it alone. 
       
      I'm wondering a couple of things. 
       
      1. Is there an easy way to "read" the status of the setting?  This would solve the problem.  Part of the challenge with this overall assignment is that there doesn't
      seem to be any sort of "control" built into these menus.  In other words, the only thing that changes in Au3Info when you hover over different options is the
      coordinates of the mouse--there aren't any unique control IDs or texts to my knowledge that differentiate between different settings or menus.  I don't know how to search for text in a menu and get an index or anything like that.  I've attached my code at the bottom and commented-out two ideas I had for reading the status and acting accordingly after "Send (Q)".  Neither of which were fruitful. 
       
      2. Is there an alternative to the overall method I've chosen that is simpler and more robust?  It seems like there must be an alternative path to these settings besides the system tray, but I don't know of any such paths.   The final script is going to be used on a number of computers which may have the McAfee icon either hidden or visible in the system tray, but currently my script only works if it is visible.  I haven't figured out how to access hidden icons with mouse clicks yet. 
       
      I should also mention that most of my code for step 1 (find the McAfee icon) comes from something I found online.  I've stared at it for a while, and I think I know how it works, but I wouldn't have known those GUI commands existed and wouldn't have been able to write that bit of code on my own.    I don't want you to overestimate my understanding of AutoIt.  Sorry for the long post, just wanted to provide all the relevant info. 
       
      Any advice you can offer would be greatly appreciated!  Thanks in advance.
      -Cody
       
      #cs AutoIt McAfee disable #ce #Include <GuiToolBar.au3> #Include <GUIConstants.au3> Local $Array[3] For $Element In $Array Global $hSysTray_Handle, $iSystray_ButtonNumber Global $sToolTipTitle = "McAfee status: OK" ; <<<<<<<<<<<<<<<< Enter some tooltip text for the icon you want here $iSystray_ButtonNumber = Get_Systray_Index($sToolTipTitle) If $iSystray_ButtonNumber = 0 Then MsgBox(16, "Error", "Icon not found in system tray") Exit Else Sleep(500) _GUICtrlToolbar_ClickButton($hSysTray_Handle, $iSystray_ButtonNumber, "right") EndIf Send( "Q" ) ;$DropDownHandle = Controlgethandle( "", "Host IPS - on", "") ;$text = ControlGetText( "", "Host IPS - on", "") ;If "Host IPS - on" = 1 Then ; Send( $Element ) ;EndIf Next Exit ;........ Func Get_Systray_Index($sToolTipTitle) ; Find systray handle $hSysTray_Handle = ControlGetHandle('[Class:Shell_TrayWnd]', '', '[Class:ToolbarWindow32;Instance:1]') If @error Then MsgBox(16, "Error", "System tray not found") Exit EndIf ; Get systray item count Local $iSystray_ButCount = _GUICtrlToolbar_ButtonCount($hSysTray_Handle) If $iSystray_ButCount = 0 Then MsgBox(16, "Error", "No items found in system tray") Exit EndIf ; Look for wanted tooltip For $iSystray_ButtonNumber = 0 To $iSystray_ButCount - 1 If StringInStr(_GUICtrlToolbar_GetButtonText($hSysTray_Handle, $iSystray_ButtonNumber), $sToolTipTitle) = 1 Then ExitLoop Next If $iSystray_ButtonNumber = $iSystray_ButCount Then Return 0 ; Not found Else Return $iSystray_ButtonNumber ; Found EndIf EndFunc  

    • pinkfoyd
      By pinkfoyd
      Hi,
       
      I remember a script where i had seen an user inverse state of a button ( $GUI_ENABLE (64)   /  $GUI_DISABLE (128) ) in one line only
      I remember it use Bit operation but i cannot reproduce it, can someone help ?
       
      In fact if the button is enable i want to disable it and if he is disable , want to enable it, something like that :
       
      GuiCtrlSetState ( $button , BitOr ( GuiCtrlGetSate ( $button ) )        ; i know this is NOT working, for explanation only
       
       
      Thanks !
    • TheAutomator
      By TheAutomator
      Hi, i'm not a very educated guy when it comes to dll calls..
      can someone help me do this:
      DllCall("uxtheme.dll", "none", "SetThemeAppProperties", "int", false) for only one control?
    • wakillon
      By wakillon
      A little animated Screensaver based on FavIcons