如何知道应用程序是否在可可Swift中有可见窗口?

dgiusagp  于 2023-03-28  发布在  Swift
关注(0)|答案(1)|浏览(108)

AppDelegate中有一个类似这样的方法:

func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
    return true
}

通过使用这个函数,在这个函数中,我们可以得到hasVisibleWindows的true或false,我的问题是,我想在函数之外访问hasVisibleWindows的值,而且函数工作的方式是,我们应该点击图标来使函数工作,在我的问题中,我想在不点击图标的情况下获得hasVisibleWindows的值,有没有其他方法可以知道应用程序NSApplication.shared是否有可见的窗口?
更新:

import Cocoa

class AppDelegate: NSObject, NSApplicationDelegate {
    
    private lazy var window1: NSWindow = NSWindow()
    private lazy var window2: NSWindow = NSWindow()

    func applicationDidFinishLaunching(_ aNotification: Notification) {
        buildWindow()
    }
    
    private func buildWindow() {

        window1 = makeWindow(title: "Window 1", isReleasedWhenClosed: false)
        window2 = makeWindow(title: "Window 2", isReleasedWhenClosed: false)

        // You can close the windows or minimize them and it will return false, if you let just 1 window open it will return true.
        // You can try all posibale things in 5 sec, close both windows or minimize both or what you like.
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + DispatchTimeInterval.seconds(5)) {
            print(nsApplication.hasVisibleWindows)
        }
        
    }
    
}

@discardableResult
func makeWindow(title: String, isReleasedWhenClosed: Bool) -> NSWindow {
    
    let window: NSWindow = NSWindow()
    window.styleMask = [.titled, .closable, .miniaturizable, .resizable]
    window.backingType = .buffered
    window.isReleasedWhenClosed = isReleasedWhenClosed
    
    window.setFrame(CGRect(origin: .zero, size: CGSize(width: 400.0, height: 200.0)), display: true)
    window.title = title
    window.center()
    window.setFrameAutosaveName(window.title)
    window.isMovableByWindowBackground = true
    window.makeKeyAndOrderFront(window)
    return window
    
}

extension NSApplication {
    
    var hasVisibleWindows: Bool {

        for item in NSApplication.shared.orderedWindows {
            if (item.isVisible) { return true }
        }
        return false
        
    }
    
}


// main part:

let nsApplication: NSApplication = NSApplication.shared
let appDelegate: AppDelegate = AppDelegate()
nsApplication.delegate = appDelegate
nsApplication.run()
6ojccjat

6ojccjat1#

NSApplication有一个windows数组。你想要的值只是这个数组是否包含任何isVisible为true的东西。
如果你想匹配flag参数的行为,你还需要检查isMiniaturized,因为很明显,有一个小型化的窗口也会导致true被传递给标志。
来自applicationShouldHandleReopendocs
小型化窗口,Dock中的窗口,被认为是可见的,并导致flag返回true,尽管小型化窗口在发送isVisible消息时返回false。
所以表达式应该是:

NSApplication.shared.windows.contains { $0.isVisible || $0.isMiniaturized }

相关问题