You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

macOS系统下如何接收显示器单独休眠的事件通知?

解决方案

1. 直接监听显示器休眠/唤醒的AppKit原生API

你可以直接使用AppKit中NSWorkspace提供的专属通知,完全符合你的需求,无需依赖底层IOKit接口:

  • 显示器休眠时触发:NSWorkspaceScreensDidSleepNotification
  • 显示器唤醒时触发:NSWorkspaceScreensDidWakeNotification

调用注意事项

需要监听NSWorkspace自带的通知中心,而非系统全局通知中心,否则无法收到回调:

Objective-C 示例代码

// 注册显示器休眠通知
[[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self 
                                                       selector:@selector(screensDidSleep:) 
                                                           name:NSWorkspaceScreensDidSleepNotification 
                                                         object:nil];
// 注册显示器唤醒通知
[[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self 
                                                       selector:@selector(screensDidWake:) 
                                                           name:NSWorkspaceScreensDidWakeNotification 
                                                         object:nil];

Swift 示例代码

// 注册显示器休眠通知
NSWorkspace.shared.notificationCenter.addObserver(self,
                                                  selector: #selector(screensDidSleep(_:)),
                                                  name: NSWorkspace.screensDidSleepNotification,
                                                  object: nil)
// 注册显示器唤醒通知
NSWorkspace.shared.notificationCenter.addObserver(self,
                                                  selector: #selector(screensDidWake(_:)),
                                                  name: NSWorkspace.screensDidWakeNotification,
                                                  object: nil)

2. 轮询方案补充

如果你的场景需要做状态校验,可以在收到上述NSWorkspace通知后调用CGDisplayIsAsleep()验证主显示器状态即可,无需额外寻找其他同步触发通知。

你提到的CGDisplayRegisterReconfigurationCallback不会触发是正常现象:该回调仅会在显示器物理接入/移除、分辨率/排列等配置变更时触发,显示器电源状态变更不属于配置变更范畴,因此不会触发回调。

权限说明

仅监听上述通知无需申请特殊权限,沙盒应用也可正常使用。

内容的提问来源于stack exchange,提问作者pmdj

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 14:12:02