简体   繁体   中英

How to get the list of open windows on MacOS in Swift?

Actually I'm trying to get the list of ALL open windows as next:

let options = CGWindowListOption(arrayLiteral: .excludeDesktopElements, .optionOnScreenOnly)
let windowsListInfo = CGWindowListCopyWindowInfo(options, CGWindowID(0))
let infoList = windowsListInfo as NSArray? as? [[String: AnyObject]]

but the problem here is that I'm getting also Dock or Window Server , SystemUIServer or widgets on the status bar. How can I improve my code to get avoid from those elements and to get only windows' list, as Xcode , Finder , etc.?

It seems that all visible windows have the value 0 for key kCGWindowLayer

import Cocoa

let options = CGWindowListOption(arrayLiteral: .excludeDesktopElements, .optionOnScreenOnly)
let windowsListInfo = CGWindowListCopyWindowInfo(options, CGWindowID(0))
let infoList = windowsListInfo as! [[String:Any]]
let visibleWindows = infoList.filter{ $0["kCGWindowLayer"] as! Int == 0 }

print(visibleWindows)
public static func visibleWindows() -> [NSWindow]
{
    return NSApplication.shared.windows.filter { $0.isVisible }
}

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