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()
@razic
Copy link

razic commented Sep 23, 2015

@kballard I tried to run this but getting error about being unable to compare result to 0. I'm using Xcode 7.0 (7A220) and on the GM Release of El Capitan. I can call result.rawValue and compare that with 0 though.

@leodabus
Copy link

leodabus commented Oct 6, 2015

@razic if result != CGError.Success

@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