Attribute VB_Name = "modTrayIcon"
Option Explicit

'Windows API's


'Have we initialized TaskbarRestart yet?
Private m_bMessageInited As Boolean
'Windows message sent out when the taskbar is restarted
' (ie4 and up)
Private m_uTaskbarRestart As Long

'Dummy function to allow AddressOf to assign to a variable
Public Function Pass(n As Long) As Long
    Pass = n
End Function

'Return a VB object pointed by nPointer
Public Function DeRef(nPointer As Long) As clsTrayIcon
    CopyMemory VarPtr(DeRef), VarPtr(nPointer), 4
End Function

'Creates a pointer to a VB object
Public Function CreateRef(obj As clsTrayIcon) As Long
    CopyMemory VarPtr(CreateRef), VarPtr(obj), 4
End Function

'Destroys a VB object created by DeRef (otherwise the VB's
'  reference count would be incorrect)
Public Sub DestroyRef(nobj As Long)
    Dim n As Long
    CopyMemory nobj, VarPtr(n), 4
End Sub

'The window procedure for the dummy windows that clsTrayIcon creates
Public Function InTrayWndProc(ByVal hwnd As Long, ByVal uMsg As Long, _
       ByVal wParam As Long, ByVal lParam As Long) As Long
    
    Dim lpObj As Long
    Dim obj As clsTrayIcon
    
    If Not m_bMessageInited Then
        InitMessage
    End If
    
    Select Case uMsg
        'Pass WM_USER_SYSTRAY to the clsTrayIcon object
        Case WM_USER_SYSTRAY
            lpObj = GetWindowLong(hwnd, GWL_USERDATA)
            Set obj = DeRef(lpObj)
            obj.ProcessMessage wParam, lParam
            DestroyRef VarPtr(obj)
        'If the TaskBar restarts, let clsTrayIcon know about it
        Case m_uTaskbarRestart
            lpObj = GetWindowLong(hwnd, GWL_USERDATA)
            Set obj = DeRef(lpObj)
            obj.RecreateIcon
            DestroyRef VarPtr(obj)
    End Select
    
    InTrayWndProc = DefWindowProc(hwnd, uMsg, wParam, lParam)
    
End Function

'Register the windows message TaskbarCreated so we can watch for it
Private Function InitMessage()
    
    m_bMessageInited = True
    
    m_uTaskbarRestart = RegisterWindowMessage("TaskbarCreated")
    
End Function

