Jump to content
Sign in to follow this  
AndyS01

Get notification when going into hibernate/sleep mode

Recommended Posts

AndyS01

I have a script that monitors network up/down time and when my laptop is set to hibernate or sleep, then later started up again, my script counts all of the hibernate/sleep time as down time.

If I could get notification when going into hibernate/sleep mode and when it resumes normal mode, I could stop looking until normal mode is resumed.

Is there an API that does this, or perhaps an event I could register a handler for?

Andy

Share this post


Link to post
Share on other sites
Jos

Run this script in SciTE and go into sleep and return from sleep... you will see notifications in the console.

#include <WindowsConstants.au3>
#include <GUIConstants.au3>
#include <date.au3>
;~ #define PBT_APMQUERYSUSPEND           0x0000
;~ #define PBT_APMQUERYSTANDBY           0x0001
;~ #define PBT_APMQUERYSUSPENDFAILED     0x0002
;~ #define PBT_APMQUERYSTANDBYFAILED     0x0003
;~ #define PBT_APMSUSPEND                0x0004
;~ #define PBT_APMSTANDBY                0x0005
;~ #define PBT_APMRESUMECRITICAL         0x0006
;~ #define PBT_APMRESUMESUSPEND      0x0007
;~ #define PBT_APMRESUMESTANDBY      0x0008
;~ #define PBTF_APMRESUMEFROMFAILURE     0x00000001
;~ #define PBT_APMBATTERYLOW             0x0009
;~ #define PBT_APMPOWERSTATUSCHANGE  0x000A
;~ #define PBT_APMOEMEVENT               0x000B
;~ #define PBT_APMRESUMEAUTOMATIC        0x0012
Global $PBT_APMSUSPEND = 0x0004
Global $PBT_APMRESUMESUSPEND = 0x0007
Global $PBT_APMSTANDBY = 0x0005
Global $PBT_APMRESUMESTANDBY = 0x0008

$hGUI    = GUICreate("Test", 100, 100,1,1)
GUIRegisterMsg($WM_POWERBROADCAST, "Standby")
GUIRegisterMsg($WM_QUERYENDSESSION, "Shutdown")
;~ GUISetState()
While 1
Sleep(10)
;~ $GUIMsg = GUIGetMsg()
;~   Switch $GUIMsg
;~       Case $GUI_EVENT_CLOSE
;~           ExitLoop
;~   EndSwitch
WEnd
;
Exit
;
Func Standby($hWnd, $Msg, $wParam, $lParam)
ConsoleWrite(_NowTime() & ": " & $wParam & @LF)
Select
Case $wParam = $PBT_APMSUSPEND
ConsoleWrite(" You going into Suspend." & @LF)
Case $wParam = $PBT_APMRESUMESUSPEND
ConsoleWrite(" You just woke up from Suspend." & @LF)
Case $wParam = $PBT_APMRESUMESTANDBY
ConsoleWrite(" You are going into Standby." & @LF)
Case $wParam = $PBT_APMRESUMESTANDBY
ConsoleWrite(" You just woke up from Standby." & @LF)
;MsgBox(0,"Hello Back", " You just woke up from Standby")
Case Else
EndSelect
EndFunc

Jos :)

Edited by Jos
  • Like 1

SciTE4AutoIt3 Full installer Download page   - Beta files       Read before posting     How to post scriptsource        Forum Rules
 
Live for the present,
Dream of the future,
Learn from the past.
  :)

Share this post


Link to post
Share on other sites
guinness

Excellent code Jos. Will be adding that to my snippet collection.


UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_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: 22/04/2018

Share this post


Link to post
Share on other sites
AndyS01

Thank you Jos, that did the trick.

Share this post


Link to post
Share on other sites
matwachich

Thanks for the code, but it has some strange behaviour:

First, here is my code (I'm trying to make an UDF)

; Veille
Global $PBT_APMSUSPEND = 0x0004
Global $PBT_APMRESUMEAUTOMATIC = 0x0012 ; Toujours envoyé à la sortie de veille
Global $PBT_APMRESUMESUSPEND = 0x0007 ; Envoyé si c'est l'utilisateur qui a provoqué la sortie de veille
; Veille prolongée
Global $PBT_APMSTANDBY = 0x0005
Global $PBT_APMRESUMESTANDBY = 0x0008
; Etat batterie et secteur
Global $PBT_APMPOWERSTATUSCHANGE = 0x000A ; Utiliser GetSystemPowerStatus pour plus de détails sur l'event
; ---
Global $__gPowerStatus_sCallBack = ""
Global $__gPowerStatus_hGUI = 0
Global $__gPowerStatus_iIsUserGUI = 0
_PowerStatus_Register("test")
While 1
Sleep(500)
WEnd
Func _PowerStatus_Register($sFunc = "", $hGUI = Default)
If $sFunc Then
  $__gPowerStatus_sCallBack = $sFunc
  If $hGUI = Default Then
   $__gPowerStatus_hGUI = GUICreate('__PowerStatus_WM_POWERBROADCAST_Window')
   $__gPowerStatus_iIsUserGUI = 0
  Else
   $__gPowerStatus_hGUI = $hGUI
   $__gPowerStatus_iIsUserGUI = 1
  EndIf
  GUIRegisterMsg(0x218, "__PowerStatus_WM_POWERBROADCAST") ; WM_POWERBROADCAST
Else
  $__gPowerStatus_sCallBack = ""
  If Not $__gPowerStatus_iIsUserGUI Then
   GUIDelete($__gPowerStatus_hGUI)
  EndIf
  $__gPowerStatus_hGUI = 0
  $__gPowerStatus_iIsUserGUI = 0
EndIf
Return 1
EndFunc
; ---
Func __PowerStatus_WM_POWERBROADCAST($hWnd, $Msg, $wParam, $lParam)
If $hWnd <> $__gPowerStatus_hGUI Then Return
If $Msg <> 0x218 Then Return ; Not WM_POWERBROADCAST
If Not $__gPowerStatus_sCallBack Then Return
; ---
Switch $wParam
  Case $PBT_APMSUSPEND
   ConsoleWrite("Mise en veille" & @CRLF) ; En veille (sleep on)
  Case $PBT_APMRESUMEAUTOMATIC
   ConsoleWrite("Sortie de veille" & @CRLF) ; (sleep off)
  ; ---
  Case $PBT_APMRESUMESTANDBY
   ConsoleWrite("Mise en veille prolongée" & @CRLF) ; Veille prolongée (standby on)
  Case $PBT_APMRESUMESTANDBY
   ConsoleWrite("Sortie de veille prolongée" & @CRLF) ; (standby off)
  ; ---
  Case $PBT_APMPOWERSTATUSCHANGE
   ConsoleWrite("Changement dans l'alimentation:" & @CRLF) ; Power status change
   ; ---
   Local $tagSYSTEM_POWER_STATUS = _
    "byte ACLineStatus;" & _
    "byte BatteryFlag;" & _
    "byte BatteryLifePercent;" & _
    "byte Reserved1;" & _
    "dword BatteryLifeTime;" & _
    "dword BatteryFullLifeTime"
   Local $tSystemPowerStatus = DllStructCreate($tagSYSTEM_POWER_STATUS)
   DllCall("Kernel32.dll", "bool", "GetSystemPowerStatus", "struct*", $tSystemPowerStatus)
   If Not @error Then
    ConsoleWrite(" ACLineStatus = " & DllStructGetData($tSystemPowerStatus, 1) & @CRLF)
    ConsoleWrite(" BatteryFlag = " & DllStructGetData($tSystemPowerStatus, 2) & @CRLF)
    ConsoleWrite(" BatteryLifePercent = " & DllStructGetData($tSystemPowerStatus, 3) & @CRLF)
    ConsoleWrite(" BatteryLifeTime = " & DllStructGetData($tSystemPowerStatus, 5) & @CRLF)
    ConsoleWrite(" BatteryFullLifeTime = " & DllStructGetData($tSystemPowerStatus, 6) & @CRLF)
   EndIf
EndSwitch
EndFunc

Everything works well, but when I go on StandBy, It's the sleeping messages that are fired ($PBT_APMSUSPEND and $PBT_APMRESUMEAUTOMATIC) instead of the StandBy message ($PBT_APMRESUMESTANDBY)

Anyone? Thanks

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
Sign in to follow this  

  • Similar Content

    • mistersquirrle
      By mistersquirrle
      TL;DR: Anyway to bypass built in sleep on TrayGetMsg() and GUIGetMsg() ?
       
      I'm currently working on a project that does some heavy array/ GDI+ processing, which depending what I have it do can take between 4s - 1min. During this time, I'd like to have the Tray icon (mainly, possibly also the GUI) for the program be responsive, so that if someone wanted to change actions or exit the script during this, they can without closing the process.
       
      Currently I have my TrayGetMsg and GUIGetMsg captures in my main program loop, working great, and once I go into the array/ GDI+ functions I tried switching it to an AdlibRegister call, unregistering it once completed. The problem with this is that it's adding ~10-20% more time into those functions, which I'd like to avoid. As I understand it, and from the helpfile: "This function automatically idles the CPU when required so that it can be safely used in tight loops without hogging all the CPU." From what I've read/ seen/ tested, this adds a 10ms sleep into the calls. I would rather avoid that sleep all together.
       
      The array/ GDI+ function that I'm doing peg the CPU at 100% (for its core) anyways, so that's not a concern of mine. My only concern for this is speed (and having things be responsive to other actions).
       
      Here's an example:
      Local $iBlockSize = 20, $iWidth = 1920, $iHeight = 1080, $aBigArray[$iWidth * $iHeight], $iPercentDone, $sLastMsg Local $aSmallerArray[Int(Ceiling($iWidth / $iBlockSize)) * Int(Ceiling($iHeight / $iBlockSize))] Local $sAdlib[] = ["Registered: ", "UnRegistered: ", "Registered to _FakeTray: "], $timer, $iIndexLength = UBound($aBigArray) Local $ixBlocks = Int(Ceiling($iWidth / $iBlockSize)), $iBlockIndex, $iBlockX, $iBlockY For $j = 0 To 2 If $j = 0 Then AdlibRegister("_CheckTray", 100) ElseIf $j = 1 Then AdlibUnRegister("_CheckTray") ElseIf $j = 2 Then AdlibRegister("_FakeTray", 100) EndIf $timer = TimerInit() For $i = 0 To $iIndexLength - 1 ; Loop through $aBigArray $aBigArray[$i] = Random(1, 10, 1) $iPercentDone = Floor(($i / $iIndexLength * 100)) ; Hopefully quick maths to get progress If $sLastMsg <> "We are " & $iPercentDone & "% done" Then ; Check if we're on a new percent $sLastMsg = "We are " & $iPercentDone & "% done" ; If so, update the msg ToolTip($sLastMsg, 0, 0) ; And display the current progress EndIf $y = Floor($i / $iWidth) ; Convert index to Y coordinate $x = Floor($i - ($y * $iWidth)) ; Convert index to X coordinate $iBlockX = Floor($x / $iBlockSize) ; Convert X coord to xBlock coord $iBlockY = Floor($y / $iBlockSize) ; Convert Y coord to yBlock coord $iBlockIndex = Int($iBlockX + ($iBlockY * $ixBlocks)) ; Convert into a blockIndex ;~ If Mod($i, 10000) = 0 Then ;~ ConsoleWrite($iBlockIndex & " - " & $i & @CRLF) ;~ EndIf $aSmallerArray[$iBlockIndex] += Int($aBigArray[$i]) ; Add into $aSmallerArray Next ConsoleWrite("Time to run with Adlib" & $sAdlib[$j] & TimerDiff($timer) & @CRLF) Next Func _CheckTray() Switch TrayGetMsg() Case "Meow" Return Case "Woof" Return EndSwitch EndFunc ;==>_CheckTray Func _FakeTray() Local $sMeow = "Oink" Switch $sMeow Case "Meow" Return Case "Woof" Return EndSwitch EndFunc ;==>_FakeTray Exit On my system, this takes ~1 minute to run, output:
       
      Time to run with AdlibRegistered: 19649.335 Time to run with AdlibUnRegistered: 16264.4124 Time to run with AdlibRegistered to _FakeTray: 16860.1283 >Exit code: 0 Time: 53.92 As you can see, it's ~20.8% faster without the Adlib check, and ~16.5% faster using a (hopefully) reproduction of TrayGetMsg() without the built in sleep. These timings vary, but it's consistently much faster without the TrayGetMsg() sleep (unless it's just that slow). I've used the OnEventModes, and those also slow down performance, more so than just using the GetMsgs, so those are out (but effective, and pretty easy to use).
    • AndreyS
      By AndreyS
      Jos suggested in one of the themes the following code:
      #include <WindowsConstants.au3> #include <GUIConstants.au3> #include <Date.au3> Global $PBT_APMSUSPEND = 0x0004 Global $PBT_APMRESUMESUSPEND = 0x0007 Global $PBT_APMSTANDBY = 0x0005 Global $PBT_APMRESUMESTANDBY = 0x0008 Dim $hGUI = GUICreate("Test", 100, 100,1,1) ;You need to work without this line. GUIRegisterMsg($WM_MOUSEWHEEL, "Standby") Func Standby($hWnd, $Msg, $wParam, $lParam) ConsoleWrite(_NowTime() & ": " & $wParam & @LF) Select Case $wParam = $PBT_APMSUSPEND ConsoleWrite(" You going into Suspend." & @LF) Case $wParam = $PBT_APMRESUMESUSPEND ConsoleWrite(" You just woke up from Suspend." & @LF) Case $wParam = $PBT_APMSTANDBY ConsoleWrite(" You are going into Standby." & @LF) Case $wParam = $PBT_APMRESUMESTANDBY ConsoleWrite(" You just woke up from Standby." & @LF) Case Else EndSelect EndFunc My application does not use any windows. It has only a menu in the tray. Tell me, who knows how to make this code work in my case.
      Thank you!
    • Nareshm
      By Nareshm
      I have script Like This :
      Opt("TrayAutoPause",0)
      $var = Ping("www.google.com")
      If not @error Then
      WinActivate ( "testapp")
      ControlClick ( "testapp", "", "[Savetest]")
      ControlSend ( " :: Gujarat TPDS  - eFPS :: Version - 2.2.0.0  - [eFPS Bill]", "", "[NAME:btnSavebyFP]", "{enter}")
      WinWait(":: Aadhar/EID/Verification Number Entry ::")
      ControlClick(":: Aadhar/EID/Verification Number Entry ::", "", "[NAME:btnNext]")
      If WinExists ("Aadhar : Length Check") Then
         ControlClick("Aadhar : Length Check", "", "[CLASS:Button; INSTANCE:1]")
         ControlSend(":: Aadhar/EID/Verification Number Entry ::", "", "[NAME:txtAadharNumber]", "{backspace}")
         ControlSend(":: Aadhar/EID/Verification Number Entry ::", "", "[NAME:txtAadharNumber]", "^v")
         ControlClick(":: Aadhar/EID/Verification Number Entry ::", "", "[NAME:btnNext]")
         WinWait(" :: Barcoded Ration Card Members - Biometric Verification/Check Utility ::")
         ControlSend("[Class:WindowsForms10.Window.8.app.0.378734a]", "", "[NAME:PictureBox2]", "{tab} {enter}")
         Sleep(5600)
         RunWait("rasdial /disconnect", "", @SW_HIDE) ; Stop connect from start
         RunWait("rasdial Internet", "", @SW_HIDE) ; Connect again
         Exit
      EndIf
      WinWait(" :: Barcoded Ration Card Members - Biometric Verification/Check Utility ::", "", 1)
      ControlSend("[Class:WindowsForms10.Window.8.app.0.378734a]", "", "[NAME:PictureBox2]", "{tab} {enter}")
      Sleep(5600)
      RunWait("rasdial /disconnect", "", @SW_HIDE) ; Stop connect from start
      RunWait("rasdial Internet", "", @SW_HIDE) ; Connect again
      Exit
      Else
         #include <MsgBoxConstants.au3>
         MsgBox($MB_TOPMOST, "Connection Status", "Internet is not Connected")
      Exit
      Endif
    • Nareshm
      By Nareshm
      How can i add sleep command using internet speed.
      If my internet speed is 40-50Kbps then sleep for 5 seconds,
      If my internet speed is 30-40Kbps then sleep for 4 seconds,
      If my internet speed is 20-30Kbps then sleep for 3 seconds.

      *Sleep command used bitween my costom script, Example,
      RunWait("rasdial /disconnect", "", @SW_HIDE) ; Stop connect from start
      Sleep(5000)
      RunWait("rasdial Internet", "", @SW_HIDE) ; Connect again
       
    • lacamel
      By lacamel
      Hi there,
      I did a short script to simulate mouse click when pixel change is detected on a small section of the screen. I recorded the screen many times to see the accuracy of the script and it seems though response time varies widely.
      Here's the script 
      $checksum = pixelchecksum (400,250, 402,252)
      While $checksum = pixelchecksum (400,250, 402,252)
      Sleep (50)
      Wend
      Sleep (300)
      Mouseclick("left", 450,300, 1, 0)
      Counting from the pixel change to the mouse click, i get response times anywhere between 370ms and 550ms. I've tried running au3 and exe, changed sleep times but never gotten an accurate response time based on the script. Any ideas why?
×