简体   繁体   中英

Open and bring new window to front when pressing NSMenuItem

I have a macOS menu application that is running as an agent (LSUIElement).

I need it to have a companion settings window. There is a "settings" NSMenuItem in the NSMenu, and the requirement is to open an actual window and bring it to the front when pressed.

The window is SwiftUI driven. Here's how it's working:

// main is an NSMenu
        main.addItem(
            withTitle: "Settings",
            action: #selector(AppDelegate.openSettings),
            keyEquivalent: "")
    @objc func openSettings() {
        let detailView = SettingsWindow(); // Swift UI view
        let controller = DetailWindowController(rootView: detailView) // See below
        controller.window?.title = "Settings";
        controller.showWindow(nil)
        NSApp.activate(ignoringOtherApps: true)
    }
class DetailWindowController<RootView : View>: NSWindowController {
    convenience init(rootView: RootView) {
        let hostingController = NSHostingController(rootView: rootView.frame(width: 400, height: 500))
        let window = NSWindow(contentViewController: hostingController)
        window.setContentSize(NSSize(width: 400, height: 500))
        self.init(window: window)
    }
}

What actually happens

The current behaviour is that the window opens, however it's always behind whatever other windows are currently in the foreground.

I need it to be in the foreground.

NSApp.activate(ignoringOtherApps: true) in the code above is an attempt to achieve this, but that didn't work.

Any help would be amazing. Many thanks.

Figured it out in the end. I needed these 3. The activation policy should be better managed, but for what it's worth here's what works.

NSApp.setActivationPolicy(.regular)
NSApp.activate(ignoringOtherApps: true)
settingsWindow!.window?.orderFrontRegardless()

In context

@objc func openSettings() {
    if(settingsWindow == nil) {
        let detailView = ActionWindow();
        settingsWindow = DetailWindowController(rootView: detailView)
        settingsWindow!.window?.title = "Cloud Brains - Settings";
        settingsWindow!.showWindow(nil)
    }
    NSApp.setActivationPolicy(.regular)
    NSApp.activate(ignoringOtherApps: true)
    settingsWindow!.window?.orderFrontRegardless()
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM