How can you detect connecting and disconnecting external monitors on Mac?
2 answers
Your answer lies in Quartz.
#include <ApplicationServices/ApplicationServices.h>
CGError CGDisplayRegisterReconfigurationCallback (
CGDisplayReconfigurationCallBack proc,
void *userInfo
);
And then your proc looks like this:
MyCGDisplayReconfigurationCallBack(
CGDirectDisplayID display,
CGDisplayChangeSummaryFlags flags,
void *userInfo) {
if (flags & kCGDisplayAddFlag || flags & kCGDisplayRemoveFlag) {
DoStuff(display, flags, userInfo);
}
}
+5
source to share
If anyone is interested in doing this in Swift 2.3, I scratched my head a bit to translate @iluvcapra's code:
let userData = UnsafeMutablePointer<ViewController>(Unmanaged.passUnretained(self).toOpaque()) //use the class name of your "self" for future reference inside the callback
CGDisplayRegisterReconfigurationCallback({ (display: UInt32, flags: CGDisplayChangeSummaryFlags, userInfo: UnsafeMutablePointer<Swift.Void>) in
let mySelf = Unmanaged<ViewController>.fromOpaque(COpaquePointer(userInfo)).takeUnretainedValue() //change here to your class name
if flags.rawValue & CGDisplayChangeSummaryFlags.AddFlag.rawValue > 0 {
//do stuff on connect
mySelf.someFunction()
} else if flags.rawValue & CGDisplayChangeSummaryFlags.RemoveFlag.rawValue > 0 {
//do stuff on disconnect
}
}, userData)
0
source to share