Any way to keep app running while keep main window hidden?

I tried many ways but it seems I just cannot get it working.

// AppDelegate
    func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
        true // false does not work either
    }

// MainWC
    func windowShouldClose(_ sender: NSWindow) -> Bool {
        print(#function)

        if sender === NSApp.mainWindow {
            print("is main window")
            sender.setIsVisible(false)
            return false
        }
        return true
    }

Once I hide the main window (using setIsVisible or orderOut) the app quits; even if I return false from applicationShouldTerminateAfterLastWindowClosed, NSApp.mainWindow will become nil.

Ah, I found out why, though it's a little embarrassing...

After so many years, I realized that NSApp.mainWindow is dynamic - it can be any window that has the key focus!

I have to create a global variable to keep instance of the initial window (as designed in main storyboard).

var mainWindow: NSWindow? // Set in MainWC.windowDidLoad

class AnotherWC: NSWindowController, NSWindowDelegate {

    override func windowDidLoad() {
        super.windowDidLoad()
        print(self.className, #function)
    }
    
    func windowShouldClose(_ sender: NSWindow) -> Bool {
        print(self.className, #function)

        return true
    }

    func windowWillClose(_ notification: Notification) {
        print(self.className, #function)

        print(mainWindow ?? "mainWindow is nil")
        mainWindow?.orderFront(nil)
    }
}
Any way to keep app running while keep main window hidden?
 
 
Q