Swift: ウィンドウのヒエラルキーを見る


デスクトップ上に表示されているウィンドウの重なり順を見ることができる。

struct Window {
    let ownerName: String
    let name: String
    let windowLayer: Int32

    var description: String {
        return "Owner Name: \(ownerName), Name: \(name), Layer: \(windowLayer)"
    }
}

func checkWindowHierarchy() {
    let windowOptions: CGWindowListOption = [
        .optionOnScreenOnly,
        .optionOnScreenBelowWindow,
        .excludeDesktopElements,
    ]
    guard let windowList = CGWindowListCopyWindowInfo(windowOptions, CGWindowID(0)),
          let array = windowList as NSArray?,
          let dictArray = array as? [[String: AnyObject]]
    else { return }
    let windows = dictArray.compactMap { (item) -> Window? in
        guard let ownerName = item[kCGWindowOwnerName as String] as? String,
              let name = item[kCGWindowName as String] as? String,
              let windowLayer = item[kCGWindowLayer as String] as? Int32
        else { return nil }
        return Window(ownerName: ownerName, name: name, windowLayer: windowLayer)
    }
    .filter { $0.windowLayer == CGWindowLevelKey.baseWindow.rawValue }
    windows.forEach { (window) in
        print(window.description)
    }
}