this.isMin.uk


맥에서 swift로 window들의 정보를 가져오는 방법

import Cocoa
import Quartz

let options:CGWindowListOption = CGWindowListOption(arrayLiteral: CGWindowListOption.excludeDesktopElements, CGWindowListOption.optionOnScreenOnly)
let relativeToWindow: CGWindowID = kCGNullWindowID

let infos = CGWindowListCopyWindowInfo(options, relativeToWindow)

struct WindowData:Codable {
    let processName: String
    let windowName: String
    let x: Int
    let y: Int
    let width: Int
    let height: Int
}
var collectedInfo: [WindowData] = []
for info in infos as! [NSDictionary] {
    let bound:NSDictionary = info["kCGWindowBounds"] as! NSDictionary
    let processName:String = info["kCGWindowOwnerName"] as? String ?? ""
    let windowName:String = info["kCGWindowName"] as? String ?? ""

    collectedInfo.append(WindowData(
        processName: processName.replacingOccurrences(of: ",", with:"\\,"),
        windowName: windowName.replacingOccurrences(of: ",", with:"\\,"),
        x:bound["X"] as? Int ?? -10000,
        y:bound["Y"] as? Int ?? -10000,
        width:bound["width"] as? Int ?? -10000,
        height:bound["hwight"] as? Int ?? -10000
    ))
}

if let jsonData = try? JSONEncoder().encode(collectedInfo), let jsonString = String(data: jsonData, encoding: .utf8) {
    print(jsonString)
}
Til, Swift, Osx