4

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

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

4

2 回答 2

6

你的答案在于石英。

#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);
    }
}

在 Swift5 中:

extension ScreenDetector {

    static let callback: CGDisplayReconfigurationCallBack = { (displayId, flags, userInfo) in
        guard let opaque = userInfo else {
            return
        }
        let mySelf = Unmanaged<ScreenDetector>.fromOpaque(opaque).takeUnretainedValue()
        
        if flags.contains(.addFlag) {
            //Add Display...
        }else if flags.contains(.removeFlag) {
            //Removed Display...
        }
        
    }

    func addObervers() {
        let userData = Unmanaged<ScreenDetector>.passUnretained(self).toOpaque()
        CGDisplayRegisterReconfigurationCallback(ScreenDetector.callback, userData)
    }
    
    func removeObservers() {
        let userData = Unmanaged<ScreenDetector>.passUnretained(self).toOpaque()
        CGDisplayRemoveReconfigurationCallback(ScreenDetector.callback, userData)
    }
}
于 2013-01-24T17:57:36.260 回答
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)
于 2016-12-01T12:41:26.080 回答