How can you detect connecting and disconnecting external monitors on Mac?

Do you have any idea how I can detect additional screens that are connected / disconnected from the Cocoa app?

I want to detect the moment when a user connects or disconnects another screen on their Mac. How can i do this?

+3


source to share


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


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







All Articles