@@ -97,6 +97,7 @@ enum JIS_VKS {
9797
9898#if MAC
9999 Foundation . NSObject keyMonitor ;
100+ Foundation . NSObject closeWindowMonitor ;
100101 uint throttleLastEventTime = 0 ;
101102#endif
102103
@@ -124,6 +125,12 @@ public CommandManager (Window root)
124125 ActionCommand c = new ActionCommand ( CommandSystemCommands . ToolbarList , "Toolbar List" , null , null , ActionType . Check ) ;
125126 c . CommandArray = true ;
126127 RegisterCommand ( c ) ;
128+
129+ closeWindowMonitor = Foundation . NSNotificationCenter . DefaultCenter . AddObserver ( AppKit . NSWindow . WillCloseNotification , ( s ) => {
130+ if ( topLevelWindows . Any ( h => h . nativeWidget == s . Object ) ) {
131+ TopLevelDestroyed ( s . Object , EventArgs . Empty ) ;
132+ }
133+ } ) ;
127134 }
128135
129136 /// <summary>
@@ -869,13 +876,18 @@ void TopLevelDestroyed (object o, EventArgs args)
869876 {
870877 RegisterUserInteraction ( ) ;
871878
872- Gtk . Window w = ( Gtk . Window ) o ;
873- w . Destroyed -= TopLevelDestroyed ;
874- w . KeyPressEvent -= OnKeyPressed ;
875- w . KeyReleaseEvent -= OnKeyReleased ;
876- w . ButtonPressEvent -= HandleButtonPressEvent ;
877- topLevelWindows . Remove ( w ) ;
879+ if ( o is Gtk . Window w ) {
880+ w . Destroyed -= TopLevelDestroyed ;
881+ w . KeyPressEvent -= OnKeyPressed ;
882+ w . KeyReleaseEvent -= OnKeyReleased ;
883+ w . ButtonPressEvent -= HandleButtonPressEvent ;
884+ topLevelWindows . Remove ( w ) ;
885+ }
878886#if MAC
887+ else if ( o is AppKit. NSWindow nsWindow) {
888+ topLevelWindows . Remove ( nsWindow ) ;
889+ }
890+
879891 if ( topLevelWindows . Count == 0 ) {
880892 if ( keyMonitor != null ) {
881893 AppKit . NSEvent . RemoveMonitor ( keyMonitor ) ;
@@ -884,7 +896,7 @@ void TopLevelDestroyed (object o, EventArgs args)
884896 }
885897#endif
886898
887- if ( w == lastFocused ? . nativeWidget )
899+ if ( o == lastFocused ? . nativeWidget )
888900 lastFocused = null ;
889901 }
890902
@@ -898,6 +910,11 @@ public void Dispose ()
898910 AppKit . NSEvent . RemoveMonitor ( keyMonitor ) ;
899911 keyMonitor = null ;
900912 }
913+
914+ if ( closeWindowMonitor != null ) {
915+ AppKit . NSEvent . RemoveMonitor ( closeWindowMonitor ) ;
916+ closeWindowMonitor = null ;
917+ }
901918#endif
902919
903920 if ( bindings != null ) {
0 commit comments