Trouble closing windows

I think I wrote this code about eight years ago and the compiled app still runs today. When I copied it into a new app today, it works if there is only one other window open, but if there are two or more open, it does not close all the windows. With three open, it leaves one. With five open, it leaves two. When I set a break point on the For statement, it says i = one less than the number I have open. I have tried it in both the CancelClose and Close events of the main window of my app. [quote]Sub Close()
dim i as Integer
i = WindowCount
for i = 0 to WindowCount-1
if Window(i) <> self Then
Window(i).Close
end if
next
End Sub[/quote]

Thinking there may be a problem with WindowCount getting changed, I tried this:[quote]Function CancelClose(appQuitting as Boolean) As Boolean
dim i, j As Integer
j = WindowCount -1
For i = 0 To j
if Window(i) <> self Then
Window(i).close
End If
Next
End Function
[/quote]It still works fine if there is one other window open, but fails if there are more. j now shows the correct value, but a NilObjectException is thrown when it tries to close the last window. Is there a better way to shut down an app. Based on my observation that closing the main window in RB would terminate the app and that that doesn’t happen in Xojo, I am guessing the answer is no.

I’m running 2014r2.1 on Win 8.1

This is the same kind of error you run into removing items from a listbox or array. As you remove items (close windows), the following entries move down to take the index space. So if you remove item 1, then item 2 becomes the new item 1. Then your code goes on to item 2 (which used to be item 3), skipping the old item 2 (which is now item 1).

The solution is to run the loop backwards.

for i = WindowCount - 1 downto 0

That works perfectly. Thanks Tim.