How to detect whether an OS X application is already launched

前端 未结 9 1619
自闭症患者
自闭症患者 2020-12-14 02:46

Normally an application bundle on OS X can only be started once, however by simply copying the bundle the same application can be launched twice. What\'s the best strategy t

9条回答
  •  忘掉有多难
    2020-12-14 03:08

    This is a combination of Romans' and Jeff's answers for Swift 2.0: If another instance of the app with the same bundle ID is already running, show an alert, activate the other instance and quit the duplicate instance.

    func applicationDidFinishLaunching(aNotification: NSNotification) {
        /* Check if another instance of this app is running. */
        let bundleID = NSBundle.mainBundle().bundleIdentifier!
        if NSRunningApplication.runningApplicationsWithBundleIdentifier(bundleID).count > 1 {
            /* Show alert. */
            let alert = NSAlert()
            alert.addButtonWithTitle("OK")
            let appName = NSBundle.mainBundle().objectForInfoDictionaryKey(kCFBundleNameKey as String) as! String
            alert.messageText = "Another copy of \(appName) is already running."
            alert.informativeText = "This copy will now quit."
            alert.alertStyle = NSAlertStyle.CriticalAlertStyle
            alert.runModal()
    
            /* Activate the other instance and terminate this instance. */
            let apps = NSRunningApplication.runningApplicationsWithBundleIdentifier(bundleID)
            for app in apps {
                if app != NSRunningApplication.currentApplication() {
                    app.activateWithOptions([.ActivateAllWindows, .ActivateIgnoringOtherApps])
                    break
                }
            }
            NSApp.terminate(nil)
        }
    
        /* ... */
    }
    

提交回复
热议问题