Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 deals only with computer sleep and not display sleep.

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

Thank you

like image 752
Nikita Rybak Avatar asked Dec 09 '25 01:12

Nikita Rybak


2 Answers

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;
   }
}
like image 85
Adam Davis Avatar answered Dec 10 '25 15:12

Adam Davis


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

like image 30
Diggory Avatar answered Dec 10 '25 16:12

Diggory



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!