Check if display is at sleep or receive sleep notifications

前端 未结 3 1587
时光说笑
时光说笑 2021-02-06 19:16

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\'

相关标签:
3条回答
  • 2021-02-06 19:55

    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 讨论(0)
  • 2021-02-06 20:03

    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;
       }
    }
    
    0 讨论(0)
  • 2021-02-06 20:21

    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

    0 讨论(0)
提交回复
热议问题