Search code examples
swiftcocoawindownswindowminimize

Programmatically minimize all windows or besides my Cocoa application?


I haven't been able to find anything about this in Swift. Is there a way to programmatically make my application minimize all other windows open in the background, or even just minimize Safari? I basically want my application to run against the desktop, without any clutter in the background. Is there a way to programmatically do this for a Cocoa app? I'm pretty new to swift, so any help would be appreciated.


Solution

  • You can use api on NSWorkspace which allows you to hide all visible app in the background. You can find more about NSWorkspace here: link

    Hides all applications other than the sender. This method must be called from your app’s main thread.

    NSWorkspace.shared().hideOtherApplications()
    

    If you only want to hide Safari,

      let appPath = NSWorkspace.shared().fullPath(forApplication: "Safari")
      let identifier = Bundle.init(path: appPath!)?.bundleIdentifier
    
      if let bundleID = identifier {
      let runningApps = NSRunningApplication.runningApplications(withBundleIdentifier:bundleID )
            if !runningApps.isEmpty {
                runningApps.first?.hide()
            }
        }