How to get running window informations in macOS

Issue #243

From https://developer.apple.com/documentation/coregraphics/1455137-cgwindowlistcopywindowinfo

Generates and returns information about the selected windows in the current user session.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
struct MyWindowInfo {
let frame: CGRect
let name: String
let pid: Int
let number: Int

init?(json: [String: Any]) {
guard let pid = json["kCGWindowOwnerPID"] as? Int else {
return nil
}

guard let name = json["kCGWindowOwnerName"] as? String else {
return nil
}

guard let rect = json["kCGWindowBounds"] as? [String: Any] else {
return nil
}

guard let x = rect["X"] as? CGFloat else {
return nil
}

guard let y = rect["Y"] as? CGFloat else {
return nil
}

guard let height = rect["Height"] as? CGFloat else {
return nil
}

guard let width = rect["Width"] as? CGFloat else {
return nil
}

guard let number = json["kCGWindowNumber"] as? Int else {
return nil
}

self.pid = pid
self.name = name
self.number = number
self.frame = CGRect(x: x, y: y, width: width, height: height)
}
}

guard let jsons = CGWindowListCopyWindowInfo(.optionAll, kCGNullWindowID) as? [[String: Any]] else {
return
}

let infos = jsons.compactMap({ MyWindowInfo(json: $0) })

Comments