开发者

Check if display is at sleep or receive sleep notifications

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's a dedicated article about wake/sleep notifications by apple, but it dea开发者_Go百科ls only with computer sleep and not display sleep.

Is there a way for application to 'hibernate' when display is at sleep?

Thank you


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, &notification);

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜