Attribute VB_Name = "SysTray"
Option Explicit

Public Sub LoadTrayIcon(SelectedPicture As Long)
    Dim t As NOTIFYICONDATA

    SysTrayHWnd = CreateWindowEx(0, "#32770", "SSBot SysTray", 0&, 0, 0, 1, 1, 0&, 0&, App.hInstance, 0&)
    SysTrayOldWndProc = SetWindowLong(SysTrayHWnd, -4, AddressOf SysTrayEvent)

    t.cbSize = Len(t)
    t.hWnd = SysTrayHWnd
    t.uId = 1&
    t.uFlags = &H2 Or &H4 Or &H1
    t.ucallbackMessage = 5150
    t.hIcon = SelectedPicture
    t.szTip = "Click to restore" + Chr(0)
    SysTraySelPicture = SelectedPicture
    Shell_NotifyIcon &H0, t

    SetTimer SysTrayHWnd, 123, 1000, AddressOf SysTrayEvent
End Sub

Public Sub UnloadTrayIcon()
    Dim t As NOTIFYICONDATA

    KillTimer SysTrayHWnd, 123

    t.cbSize = Len(t)
    t.hWnd = SysTrayHWnd
    t.uId = 1&
    Shell_NotifyIcon &H2, t

    SetWindowLong SysTrayHWnd, -4, SysTrayOldWndProc
    DestroyWindow SysTrayHWnd
End Sub

Private Function SysTrayEvent(ByVal hWnd As Long, ByVal uMsg As Long, ByVal wParam As Long, ByVal lParam As Long) As Long
    Dim t As NOTIFYICONDATA

    Select Case uMsg
        Case &H113
            t.cbSize = Len(t)
            t.hWnd = SysTrayHWnd
            t.uId = 1&
            t.uFlags = &H2
            t.hIcon = SysTraySelPicture
            Shell_NotifyIcon &H1, t
        Case 5150
            If LOWORD(lParam) <> 512 And MainFrm.WindowState = 1 Then
                MainFrm.WindowState = 0
                MainFrm.Visible = True
            End If
        Case Else
            SysTrayEvent = CallWindowProc(SysTrayOldWndProc, hWnd, uMsg, wParam, ByVal lParam)
    End Select
End Function
