Search code examples
applescriptapplescript-objc

How to click on the red "X" and minimize the app instead of closing it?


To close my app I have been using:

on applicationShouldTerminateAfterLastWindowClosed:sender
        return true
    end applicationShouldTerminateAfterLastWindowClosed:

I would like that when I click on the red "X" the application is not closed just minimize or hide to the Dock so when I click it I can open it again.


Solution

  • You can implement the following method in the application delegate to control whether the application closes when the last window is closed:

    on applicationShouldTerminateAfterLastWindowClosed:theSendingApp
        -- this keeps the application running
        return false 
    end applicationShouldTerminateAfterLastWindowClosed:
    

    Depending on the kind of app you've designed and the kind of window you're using, the app may or may not reopen its window when you reactivate it (e.g., when click on the dock item). You may need to add another method to the app delegate to handle that case:

    on applicationShouldHandleReopen:theSendingApp hasVisibleWindows:openWindowFlag
        if openWindowFlag is true then
            return true
        else
            theWindow's makeKeyAndOrderFront:me
            return true
        end if
    end applicationShouldHandleReopen:hasVisibleWindows:
    

    theWindow refers to the property in the app delegate that holds the widow reference (I believe that's what Xcode names it in the default implementation). You should check the window object in the xib: look in the Attributes Inspector and make sure the checkbox 'Released when closed' is off. You want to retain the window after it's closed so that you can open it again.