How to use the MacOS app dock menu to re-open the app that has been closed (by using the red button located on the top left corner)?

陌路散爱 提交于 2020-04-30 11:08:25

问题


Good Day, When I close my MacOS app by using the red button (located at the top left corner), the MacOS application disapears but the dock icon is still there at the bottom. If I click right on the dock icon I want to add a "Re-Open" menu item to re-open the app. Below is the code produced to a certain point... When I click on "Re-Open" it prints "XXX" in the console... because I have not found the code to re-open the app! Any help would be much appreciated to fill up the below function call reOpen(sender : NSMenuItem) Thanks

Below is my AppDelegate.swift file content:

import Cocoa
import SwiftUI

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

  var window: NSWindow!

  func applicationDidFinishLaunching(_ aNotification: Notification) {

    let contentView = ContentView()

    window = NSWindow(
      contentRect: NSRect(x: 0, y: 0, width: 480, height: 300),
      styleMask: [.titled, .closable, .miniaturizable, .resizable, .fullSizeContentView],
      backing: .buffered, defer: false)
    window.center()
    window.setFrameAutosaveName("Main Window")
    window.contentView = NSHostingView(rootView: contentView
      window.makeKeyAndOrderFront(nil)
  }

  func applicationWillTerminate(_ aNotification: Notification) {
    // Insert code here to tear down your application
  }

  func applicationDockMenu(_ sender: NSApplication) -> NSMenu? {
    let menu = NSMenu()
    let reOpenMenuItem = NSMenuItem(title:"Re-Open", action:#selector(AppDelegate.reOpen), keyEquivalent:"")
    menu.addItem(reOpenMenuItem)
    return menu
  }

  @objc func reOpen(sender : NSMenuItem) {
    print("XXX")
  }
}

回答1:


Finally the final working code to add for the reOpen function is:

@objc func reOpen(sender : NSMenuItem) {
  print("XXX")
  let url = URL(fileURLWithPath: Bundle.main.resourcePath!)
  let path = url.deletingLastPathComponent().deletingLastPathComponent().absoluteString
  let task = Process()
  task.launchPath = "/usr/bin/open"
  task.arguments = [path]
  task.launch()
  exit(0)
}

I found the code here at this link:

enter link description here



来源:https://stackoverflow.com/questions/61149135/how-to-use-the-macos-app-dock-menu-to-re-open-the-app-that-has-been-closed-by-u

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!