diff --git a/src/osx/cocoa/nonownedwnd.mm b/src/osx/cocoa/nonownedwnd.mm index 560bdd5d95..777b0bafb4 100644 --- a/src/osx/cocoa/nonownedwnd.mm +++ b/src/osx/cocoa/nonownedwnd.mm @@ -492,6 +492,15 @@ extern int wxOSXGetIdFromSelector(SEL action ); wxNonOwnedWindowCocoaImpl* windowimpl = [window WX_implementation]; if ( windowimpl ) { + // See windowDidResignKey: -- we emulate corresponding focus set + // event for the first responder here as well: + NSView *firstResponder = [window firstResponder]; + wxWidgetCocoaImpl *focused = firstResponder + ? (wxWidgetCocoaImpl*)wxWidgetImpl::FindFromWXWidget(wxOSXGetViewFromResponder(firstResponder)) + : NULL; + if ( focused ) + focused->DoNotifyFocusSet(); + wxNonOwnedWindow* wxpeer = windowimpl->GetWXPeer(); if ( wxpeer ) wxpeer->HandleActivated(0, true); @@ -508,10 +517,17 @@ extern int wxOSXGetIdFromSelector(SEL action ); if ( wxpeer ) { wxpeer->HandleActivated(0, false); - // as for wx the deactivation also means losing focus we - // must trigger this manually - [window makeFirstResponder:nil]; - + + // As for wx the deactivation also means losing focus, we + // must emulate focus events _without_ resetting first responder + // (because that would subtly break other things in Cocoa/macOS): + NSView *firstResponder = [window firstResponder]; + wxWidgetCocoaImpl *focused = firstResponder + ? (wxWidgetCocoaImpl*)wxWidgetImpl::FindFromWXWidget(wxOSXGetViewFromResponder(firstResponder)) + : NULL; + if ( focused ) + focused->DoNotifyFocusLost(); + // TODO Remove if no problems arise with Popup Windows #if 0 // Needed for popup window since the firstResponder diff --git a/src/osx/cocoa/window.mm b/src/osx/cocoa/window.mm index 267f3942bd..e1375beee7 100644 --- a/src/osx/cocoa/window.mm +++ b/src/osx/cocoa/window.mm @@ -71,7 +71,24 @@ NSView* GetFocusedViewInWindow( NSWindow* keyWindow ) WXWidget wxWidgetImpl::FindFocus() { - return GetFocusedViewInWindow( [NSApp keyWindow] );; + NSWindow *key = [NSApp keyWindow]; + if ( key == nil ) + { + // Application's keyWindow property may still not be updated and be + // nil when windowDidBecomeKey: is called and even if the + // just-activated's window isKeyWindow already returns YES. To get + // accurate information about where the focus is at all times, we have + // to explicitly check all application windos as well: + for ( NSWindow *w in [NSApp windows] ) + { + if ( [w isKeyWindow] ) + { + key = w; + break; + } + } + } + return key ? GetFocusedViewInWindow(key) : nil; } wxWidgetImpl* wxWidgetImpl::FindBestFromWXWidget(WXWidget control)