Skip to content

Instantly share code, notes, and snippets.

@lilyball
Last active March 6, 2022 11:18
Show Gist options
  • Save lilyball/569d5ba0f1b0961a15c0 to your computer and use it in GitHub Desktop.
Save lilyball/569d5ba0f1b0961a15c0 to your computer and use it in GitHub Desktop.
import CoreGraphics
func printDisplays() {
var displayCount: UInt32 = 0;
var result = CGGetActiveDisplayList(0, nil, &displayCount)
if (result != 0) {
println("error: \(result)")
return
}
let allocated = Int(displayCount)
var activeDisplays = UnsafeMutablePointer<CGDirectDisplayID>.alloc(allocated)
result = CGGetActiveDisplayList(displayCount, activeDisplays, &displayCount)
if (result != 0) {
println("error: \(result)")
return
}
println("\(displayCount) displays:")
for i in 0..<displayCount {
println("[\(i)] - \(activeDisplays[Int(i)])")
}
activeDisplays.dealloc(allocated)
}
printDisplays()
@nakajijapan
Copy link

-  var activeDisplays
+ let activeDisplays

@sassman
Copy link

sassman commented Apr 9, 2020

adjusted for swift 5.2:

import AVFoundation

    func printDisplays() {
        var displayCount: UInt32 = 0;
        var result = CGGetActiveDisplayList(0, nil, &displayCount)
            
        if result != .success {
            print("error: \(result)")
            return
        }

        let allocated = Int(displayCount)
        let activeDisplays = UnsafeMutablePointer<CGDirectDisplayID>.allocate(capacity: allocated)
        result = CGGetActiveDisplayList(displayCount, activeDisplays, &displayCount)
        if result != .success {
            print("error: \(result)")
            return
        }

        print("\(displayCount) displays:")
        for i in 0..<displayCount {
            print("[\(i)] - \(activeDisplays[Int(i)])")
        }
        activeDisplays.deallocate()
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment