MenuItem Cast to WindowMenuItem Problem

I just updated from Xojo 2014r3 to 2016r4.1. For many years I have used the following code to close a window which is listed in a menu item named Window.

Sub CloseThisWindow(closeMe As Window)
Dim i, count As Integer
Dim w As WindowMenuItem

	' Count how may items are in the Window menu
	count = MenuBar1.Child( "WindowMenu" ).Count - 1
	
	For i = 0 To count
			' Get a menu item
			w = WindowMenuItem( MenuBar1.Child( "WindowMenu" ).Item( i ) )
			' If the item has the window we want to close
			if w.IsWindow( closeMe ) then
					'Then remove that menu item
					MenuBar1.Child( "WindowMenu" ).Remove( i )
					'Close the window
					closeMe.Close
					' And terminate the loop
					Exit
			End
	Next

End Sub

Now every time I close a window the error “MenuItem cannot be cast to WindowMenuItem” occurs and the program aborts on the line

			w = WindowMenuItem( MenuBar1.Child( "WindowMenu" ).Item( i ) )

This is on MacOS 10.11.6 El Capitan. If I compile with Xojo 2014r3 the code works on the same OS, so it is not the OS but something from Xojo 2016r4.1 but I am unable to determine why this fails. Anyone have any ideas?

Problem fixed!

Even though WindowMenuItem was a subclass of MenuItem, Xojo 2016r4.1 accepted the routine on compilation but threw an exception as previously noted when running and a window was closed.

The problem was fixed with the following code:

	Dim i, count As Integer
	Dim m As MenuItem
	
	' Count how may items are in the Window menu
	count = MenuBar1.Child( "WindowMenu" ).Count - 1
	
	For i = 0 To count
			' Get a menu item
			m = MenuBar1.Child( "WindowMenu" ).Item( i )
			' If the item has the window we want to close
			If Window(i).Title = m.Text Then
					'Then remove that menu item
					MenuBar1.Child( "WindowMenu" ).Remove( i )
					'Close the window
					closeMe.Close
					' And terminate the loop
					Exit
			End
	Next

So consider this mystery solved.