Search code examples
macosappkitnsapplication

NSApplication make window front on app switch


When run my app(OSX, macOS SDK 10.15), it shows the main window, as expected. I then CMD-Tab to another app, but when I CMD-Tab back to my app, it won't show the window. The same happens if I click on it in the dock. I've tried various suggestions, such as:

[NSApp activateIgnoringOtherApps:YES];
[window makeKeyAndOrderFront:nil];
[window orderFrontRegardless];

and

[[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(applicationSwitchedTo) name:NSWorkspaceDidActivateApplicationNotification object:nil];

-(void)applicationSwitchedTo
{
    [window makeKeyAndOrderFront:nil];
}

I've set up all the callback methods in both the window and app delegates, but I don't get anything,except the above callback, when I switch to or from my app. I would think it would default behavior to show the apps main window when switched to it from another app. Any help is greatly appreciated!


Solution

  • I figured out a fix, but I'm not sure if it's the proper thing to do. I noticed that if I called

    [NSApp finishLaunching]
    

    then the window ordering functions don't work. I don't need it's functionality, so I removed it. Furthermore, I'm now handling the event type NSEventTypeAppKitDefined, which is called when you switch on and off the app. I then check the subtype and call the window ordering function:

    case NSEventTypeAppKitDefined:
    {
         if([theEvent subtype] == NSEventSubtypeApplicationActivated) {
              [window makeKeyAndOrderFront:nil];
         }
    }
    

    Hope this helps someone down the line!