Attribute VB_Name = "modPowerEvents"
' ----------------------------------------------------------------------------
'  Copyright (C) 2009 Noda (Yohan Lasorsa) - http://nodadev.wordpress.com
' ----------------------------------------------------------------------------
'  This software Is provided 'as-is', without any express or implied
'  warranty. In no event will the author be held liable for any damages
'  arising from the use of this software.
'
'  Permission is granted to anyone to use this software for any purpose,
'  including commercial applications, and to alter it and redistribute it
'  freely, subject to the following restrictions:
'
'  1. The origin of this software must not be misrepresented; you must not
'     claim that you wrote the original software. If you use this software
'     in a product, an acknowledgment in the product documentation would be
'     appreciated but is not required.
'  2. Altered source versions must be plainly marked as such, and must not be
'     misrepresented as being the original software.
'  3. This notice may not be removed or altered from any source distribution.
' ----------------------------------------------------------------------------

Option Explicit

Public Declare Function SetWindowLong Lib "user32" Alias "SetWindowLongA" (ByVal hwnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As Long
Public Declare Function CallWindowProc Lib "user32" Alias "CallWindowProcA" (ByVal lpPrevWndFunc As Long, ByVal hwnd As Long, ByVal Msg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long

Private Const WM_POWERBROADCAST = &H218
Public Const GWL_WNDPROC = (-4)

Private Enum ePowerBroadcastType
     PBT_APMQUERYSUSPEND = &H0
     PBT_APMQUERYSTANDBY = &H1
     PBT_APMQUERYSUSPENDFAILED = &H2
     PBT_APMQUERYSTANDBYFAILED = &H3
     PBT_APMSUSPEND = &H4
     PBT_APMSTANDBY = &H5
     PBT_APMRESUMECRITICAL = &H6
     PBT_APMRESUMESUSPEND = &H7
     PBT_APMRESUMESTANDBY = &H8
End Enum

Public oldProcAddress As Long

Public Function VB_WindowProc(ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, _
    ByVal lParam As Long) As Long

    On Local Error Resume Next
    Dim lRet As Long

    ' catch power events broadcast
    If ((wMsg = WM_POWERBROADCAST) And ( _
        (wParam = PBT_APMRESUMESUSPEND) Or (wParam = PBT_APMRESUMESTANDBY) _
        Or (wParam = PBT_APMRESUMECRITICAL))) Then
        
        ' re-init fan status
        StartFanAuto
        Sleep 100
        HDAPM = 128
        fanStatus = Unknown
        
        ' restore downscaled mode if needed
        If (modeCustom And settings.downscaling) Then
            SetDownscaling True
        End If
    End If
    VB_WindowProc = CallWindowProc(oldProcAddress, hwnd, wMsg, wParam, lParam)
End Function
