如何检测Mac上外接显示器的连接和断开连接?

时间:2013-01-24 17:35:07

标签: objective-c cocoa

您是否知道如何检测Cocoa应用程序中插入/拔出的其他屏幕?

我想检测用户将另一个屏幕插入或拔出Mac的时刻。我怎么能这样做?

2 个答案:

答案 0 :(得分:5)

你的答案在于Quartz。

#include <ApplicationServices/ApplicationServices.h>

CGError CGDisplayRegisterReconfigurationCallback (
    CGDisplayReconfigurationCallBack proc,
    void *userInfo
);

然后你的过程看起来像:

 MyCGDisplayReconfigurationCallBack(
    CGDirectDisplayID display,
    CGDisplayChangeSummaryFlags flags,
    void *userInfo) {

    if (flags & kCGDisplayAddFlag || flags & kCGDisplayRemoveFlag) {
        DoStuff(display, flags, userInfo);
    }
}

答案 1 :(得分:0)

如果有人有兴趣在Swift 2.3中这样做,我会翻阅我的脑袋一段时间来翻译@iluvcapra的代码:

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)