Attribute VB_Name = "modWMClose"
Option Explicit



' This is to restore the icon when it needs adding again
Private 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 Declare Function SetWindowLong Lib "user32" Alias "SetWindowLongA" (ByVal hWnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As Long
Const GWL_WNDPROC        As Long = (-4)
Private Const WM_CLOSE = &H10

Private lOrigWndProc As Long
Private lCurHwnd As Long

Public Sub SubClassForm(lHwnd As Long)
    If lHwnd <> 0 Then
        lOrigWndProc = SetWindowLong(lHwnd, GWL_WNDPROC, AddressOf FormWndProc)
        lCurHwnd = lHwnd
    End If
End Sub

Public Sub UnSubClassForm()
    Call SetWindowLong(lCurHwnd, GWL_WNDPROC, lOrigWndProc)
    lCurHwnd = 0
    lOrigWndProc = 0
End Sub


Private Function FormWndProc(ByVal hwndMsg As Long, ByVal uMsg As Long, _
                             ByVal wParam As Long, ByVal lParam As Long) As Long
On Error Resume Next

        ' I've worked out that the uMsg 49252 is sent when
        ' the windows systray restores after an explorer crash
        If uMsg = WM_CLOSE And lCurHwnd = hwndMsg Then
            Call DoWhateverYouNeedTo
            FormWndProc = 0
        Else
            'pass to original message handler
            FormWndProc = CallWindowProc(lOrigWndProc, hwndMsg, uMsg, wParam, lParam)
        End If
        
End Function



