J. Doe
J. Doe

Reputation: 551

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.?

Upvotes: 10

Views: 4245

Answers (2)

Paul Stevenson
Paul Stevenson

Reputation: 145

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

Upvotes: -2

vadian
vadian

Reputation: 285260

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)

Upvotes: 13

Related Questions