I have an application utility which becomes useless when there\'s no user. So, in order to save resources, I\'d like it to know when/whether display is at sleep.
There\'
Since I couldn´t find any call issued by the display falling to sleep (maybe the screensaver does that? It´s very likely to kick in before the system falls to sleep), I´d suggest detecting the idle time manually and then comparing it to the display sleep settings. This article covers how to get the idle time from IOKit and you should be able to easily get the current sleep settings, e.g. with "pmset -g | grep sleep".
Two minutes after posting the above, I discovered an open source command line tool that will probably help you a lot getting there: SleepWatcher seems to be able to do just what you asked for.
The DisplayWrangler service sends notifications for when the display will power off:
// Doesn't include error checking - just a quick example
io_service_t displayWrangler;
IONotificationPortRef notificationPort;
io_object_t notification;
displayWrangler = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceNameMatching("IODisplayWrangler");
notificationPort = IONotificationPortCreate(kIOMasterPortDefault);
IOServiceAddInterestNotification(notificationPort, displayWrangler, kIOGeneralInterest, displayPowerNotificationsCallback, NULL, ¬ification);
CFRunLoopAddSource (CFRunLoopGetCurrent(), IONotificationPortGetRunLoopSource(notificationPort), kCFRunLoopDefaultMode);
IOObjectRelease (displayWrangler);
Then the callback looks something like this:
void displayPowerNotificationsCallback(void *refcon, io_service_t service, natural_t messageType, void *messageArgument)
{
switch (messageType) {
case kIOMessageDeviceWillPowerOff :
// This is called twice - once for display dim event, then once
// for display power off
break;
case kIOMessageDeviceHasPoweredOn :
// Display powering back on
break;
}
}
This is response to a question asked a while ago - but I thought it would be useful to add my answer.
NSWorkspace has a couple of notifications for when displays wake and sleep: NSWorkspaceScreensDidSleepNotification and NSWorkspaceScreensDidWakeNotification