'* Cascading windows and instance counting 
'* By Brent D. Thorn (http://www.b6sw.com/)
'* PUBLIC DOMAIN

Global g.WindowCount

Call CascadePosition
Open "1" For Window As #1
#1 TrapCloseCommon$()

Call CascadePosition
Open "2" For Window As #2
#2 TrapCloseCommon$()

Call CascadePosition
Open "3" For Window As #3
#3 TrapCloseCommon$()

Wait

Sub CommonClose handle$
Close #handle$
g.WindowCount = g.WindowCount - 1

Print "Closed ";handle$;". ";g.WindowCount;" window(s) open."

If g.WindowCount = 0 Then
Print "End of program."

End
End If
End Sub

Function TrapCloseCommon$()
TrapCloseCommon$ = "TrapClose CommonClose"
g.WindowCount = g.WindowCount + 1
End Function

Sub CascadePosition
offset = 0

CallDLL #user32, "GetSystemMetrics", _
_SM_CYCAPTION As ULong, _
cy As Long
offset = offset + cy

CallDLL #user32, "GetSystemMetrics", _
_SM_CYSIZEFRAME As ULong, _
cy As Long
offset = offset + cy

UpperLeftX = UpperLeftX + offset
UpperLeftY = UpperLeftY + offset

If UpperLeftX + WindowWidth > DisplayWidth _
Or UpperLeftY + WindowHeight > DisplayHeight Then
UpperLeftX = 1
UpperLeftY = 1
End If
End Sub