VB调用CallWindowProc, Visual basic已停止工作?

我从网上找到下面的方法来判断电脑是否是关机,然后才决定程序退出时是否显示确认对话框,代码如下,但是每次退出程序时,就会出现“Visual basic已停止工作”,请大家帮忙看看是怎么回事

Private Sub Form_Load()

lpPrevWndProc = SetWindowLong(Me.hWnd, GWL_WNDPROC, AddressOf WindowProcShutdown)
gShutdown = False

End Sub

Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer)

Dim Temp As Long
Dim f As Form
Dim res As Long

'非关机时要求确认软件关闭操作
If gShutdown = True Then
    res = vbYes
Else
    res = MsgBox("Are you sure to exit?", vbInformation + vbYesNo + vbDefaultButton2, Caption)
End If

If res = vbNo Then
    Cancel = 1      'Cancel
Else                'res=vbYes
    '恢复原窗口函数

    Temp = SetWindowLong(Me.hWnd, GWL_WNDPROC, lpPrevWndProc)

    For Each f In Forms
        Unload f
    Next

    End     'Close

End If

End Sub

========模块==========================

Public lpPrevWndProc As Long '存放原窗口函数句柄
Public Const GWL_WNDPROC = -4& '指定替换原窗口函数常数
Public gShutdown As Boolean '关机时设置此变量从而绕过软件关闭确认对话框
Public fno As Long
'调用指定窗口函数的API函数定义
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
'设置Windows长参数的API函数定义
'(本程序中设置指定窗口函数替换原窗口函数,返回原窗口函数地址,当nIndex=GWL_WNDPROC)
Public Declare Function SetWindowLong Lib "user32" Alias "SetWindowLongA" (ByVal hWnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As Long

'我们自己的窗口函数
Public Function WindowProcShutdown(ByVal hWnd As Long, ByVal uMsg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long

If uMsg = 17 Then ' WM_QUERYENDSESSION
    gShutdown = True
Else
    If uMsg = 22 Then ' WM_ENDSESSION
        If wParam = 0 Then '代表将顺利关机或LogOff,这时便得做正常结束程序的操作
            gShutdown = True
        End If
    End If
End If
'将之送往原来的Window Procedure
WindowProcShutdown = CallWindowProc(lpPrevWndProc, hWnd, uMsg, wParam, lParam)

End Function

vb6有个缺点,用addressof传的回调函数,有任何异常,vb都不能捕获,造成的结果就是崩溃。
所以你得仔细排查
目测,你应该把
SetWindowLong(Me.hWnd, GWL_WNDPROC, lpPrevWndProc)
写在Unload里,不要写在QueryUnload