如何在Mac上检测外部显示器的连接和断开连接? [英] How can you detect the connection and disconnection of external monitors on the Mac?
本文介绍了如何在Mac上检测外部显示器的连接和断开连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您是否知道如何检测可可应用程序中插入/未插入的其他屏幕?
Do you have any idea how I can detect additional screens being plugged in / unplugged in a Cocoa application?
我想检测用户插入或插入的时刻拔出另一个屏幕到他的Mac。我该怎么办?
I want to detect the moment when the user plugs or unplugs another screen to his Mac. How could I do this?
推荐答案
您的答案就在Quartz中。
Your answer lies in Quartz.
#include <ApplicationServices/ApplicationServices.h>
CGError CGDisplayRegisterReconfigurationCallback (
CGDisplayReconfigurationCallBack proc,
void *userInfo
);
然后您的proc如下:
And then your proc looks like:
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)
}
}
这篇关于如何在Mac上检测外部显示器的连接和断开连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文