Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closing Mac application (clicking red cross on top) and reopening by clicking dock icon

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 ?

like image 320
Leo Avatar asked Mar 31 '11 10:03

Leo


People also ask

How do I close an app with red button on Mac?

in the top-left corner of the window, or press Command-W. In the menu bar, when the app is active, choose App Name > Quit App. For example, choose Mail > Quit Mail. Note: When you click the red close button in the top-left corner of an app's window, the window closes, but the app remains open.

How do you close running apps on Mac?

To quit an app, choose App Name > Quit App in the menu bar. For example, choose Preview > Quit Preview (or press the keyboard shortcut Command-Q).

How do I close Minimised windows on Mac?

On your Mac, do any of the following: Close a single window: In a window, click the red Close button in the top-left corner of the window, or press Command-W. Close all open windows for an app: Press Option-Command-W.


2 Answers

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

like image 148
Ivan Ičin Avatar answered Oct 04 '22 20:10

Ivan Ičin


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
}
like image 21
Johann Dirdal Avatar answered Oct 04 '22 20:10

Johann Dirdal