Attribute VB_Name = "modMain"
Option Explicit

Private Type TForms
    hWnd As Long
    Caption As String
End Type

Private Const SW_RESTORE = 9

Private Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" (ByVal hWnd As Long, ByVal lpString As String, ByVal cch As Long) As Long
Private Declare Function EnumWindows Lib "user32" (ByVal lpEnumFunc As Long, ByVal lParam As Long) As Long
Private Declare Function ShowWindow Lib "user32" (ByVal hWnd As Long, ByVal nCmdShow As Long) As Long
Private Declare Function SetForegroundWindow Lib "user32" (ByVal hWnd As Long) As Long

Public m_frmShapIt_DesktopImage As frmSnapIt_DesktopImage, m_frmShapIt_Desktop As frmSnapIt_Desktop, _
    g_sDefaultFolder As String, g_iiW As Long, g_iQualityJPG As Long, m_Forms() As TForms

Public Sub Main()
    If PrevInst Then Exit Sub
    
    Dim s As String

    g_sDefaultFolder = GetSetting(App.Title, "Setting", "DefaultFolder", App.Path)
    s = GetSetting(App.Title, "Setting", "QualityJPG", 70)
    If IsNumeric(s) Then g_iQualityJPG = CLng(s)
    Select Case g_iQualityJPG
        Case Is < 20: g_iQualityJPG = 20
        Case Is > 100: g_iQualityJPG = 100
    End Select

    Set m_frmShapIt_Desktop = New frmSnapIt_Desktop
    m_frmShapIt_Desktop.Show
End Sub

Private Function PrevInst() As Boolean
    Dim sTitle As String, hWnd As Long, bPaint As Boolean, sPaint As String
    
    sTitle = "Snap-It"
    App.Title = "New name"
    sPaint = sTitle & ".bmp - Paint"
    
    ReDim m_Forms(0)
    EnumWindows AddressOf Callback_EnumWindows, 0
    
    hWnd = WindowFind(sPaint): bPaint = hWnd
    If hWnd = 0 Then hWnd = WindowFind(sTitle & "_W")
    If hWnd = 0 Then hWnd = WindowFind(sTitle & " Options")
    If hWnd = 0 Then hWnd = WindowFind(sTitle & "_D")
    If hWnd = 0 Then hWnd = WindowFind(sTitle)
    If hWnd = 0 Then
        App.Title = sTitle
    Else
        If bPaint Then sTitle = sPaint
        If Not WindowFind(sTitle & "_D") Then
            ShowWindow hWnd, SW_RESTORE
            SetForegroundWindow hWnd
        End If
        PrevInst = True
    End If
End Function

Private Function WindowFind(sCaption) As Long
    Dim i As Long
    For i = 1 To UBound(m_Forms)
        If sCaption = m_Forms(i).Caption Then
            WindowFind = m_Forms(i).hWnd
            Exit Function
        End If
    Next i
End Function

Public Function Callback_EnumWindows(ByVal hWnd As Long, ByVal lpData As Long) As Long
    Dim cnt As Long, i As Long, sTitle As String * 256
    
    cnt = GetWindowText(hWnd, sTitle, 255)
    ' Find Next Window
    If cnt > 0 Then
        If Left$(sTitle, 7) = "Snap-It" Then
            i = UBound(m_Forms) + 1
            ReDim Preserve m_Forms(i)
            m_Forms(i).Caption = Left$(sTitle, cnt)
            m_Forms(i).hWnd = hWnd
        End If
    End If
    Callback_EnumWindows = 1
End Function
