12

When I close my Mac application (by clicking red cross button on window top bar) the app icon stays in the dock at the bottom. Now this is normal behaviour. When user click on it again it does not fire up the application unless the user quits the application altogether and relaunches it again.

A similar example on Mac OS X is "Activity Monitor". You can close the application by clicking the red cross button at the top the but dock icon stays there. User can re-open it by clicking dock icon.

How can I achieve this in my own application ?

Paul R
  • 208,748
  • 37
  • 389
  • 560
Leo
  • 1,547
  • 3
  • 24
  • 40

3 Answers3

22

If you are still concerned how to reopen the window that you have closed, use this method:

- (BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication hasVisibleWindows:(BOOL)flag {

[window makeKeyAndOrderFront:self];

return YES;
}

You can use this to handle clicks on the applications icon in the dock.

For further information check out the NSApplicationDelegate Protocol Reference.

Here is the documentation:

http://developer.apple.com/library/mac/#documentation/cocoa/reference/NSApplicationDelegate_Protocol/Reference/Reference.html

Hope this helps!

Latest Update:

In latest Xcode 11.4 on MacOS 10.15 with Swift 5.2, this same problem exists in MacOS SwiftUI app. Adding following code inside AppDelegates.swift solves the issue.

func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
    if !flag{
        window.makeKeyAndOrderFront(nil)
    }
    return true
}
NikzJon
  • 912
  • 7
  • 25
Johann Dirdal
  • 1,100
  • 6
  • 12
3

Implement the method

- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)sender
{ 
return NO; 
}

in your app delegate

Your app will hang around after the window is closed and then if you implement

- (void)applicationDidBecomeActive:(NSNotification *)aNotification
{
//dock icon has just been clicked , or cmd-tabbed into
}

in the app delegate

You can do things when the icon is clicked such as open a new or old window if you need to

See http://developer.apple.com/library/mac/#documentation/cocoa/reference/NSApplicationDelegate_Protocol/Reference/Reference.html for other relevant application events

Warren Burton
  • 17,451
  • 3
  • 53
  • 73
  • He is saying that in applicationDidBecomeActive you can see if the app is windowless, and if it is, open a new blank window (or similar). – Tom Andersen Mar 31 '11 at 12:35
2

I think that the answers above aren't fully correct, to achieve this you should override applicationShouldHandleReopen(_:hasVisibleWindows:) https://developer.apple.com/reference/appkit/nsapplicationdelegate/1428638-applicationshouldhandlereopen

Ivan Ičin
  • 9,672
  • 5
  • 36
  • 57