kIOMessageDeviceWillPowerOff notification doesn't work as expected

Hello,

I try to get notifications when the display is turned off (not the screensaver). I've tried the following code (part of it), but it don't work at all (the callback is never called).. I don't get where I did something wrong. Any help or relevant documentation link would be very appreciated ..

Thank, volfo

    io_object_t            disp_notifierObject;
    void*                  disp_refCon = NULL;  
    kern_return_t          disp_registerCode;

    notifyPortRef = IONotificationPortCreate(kIOMainPortDefault);
    display_wrangler = IOServiceGetMatchingService(
        kIOMainPortDefault,
        IOServiceNameMatching("IODisplayWrangler"));
    
    // register to receive display sleep notifications
    disp_registerCode = IOServiceAddInterestNotification(
        notifyPortRef, 
        display_wrangler, 
        kIOGeneralInterest, 
        CBDisplaySleep, 
        NULL, 
        &disp_notifierObject);
    if ( disp_registerCode != kIOReturnSuccess ) {
        printf("IOServiceAddInterestNotification failed\n");
        return 2;
    }

    CFRunLoopAddSource( 
        CFRunLoopGetCurrent(),
        IONotificationPortGetRunLoopSource(notifyPortRef),
        kCFRunLoopCommonModes );
    IOObjectRelease (display_wrangler);

Replies

Do you really want to know when the display is turned OFF (by a user)? Because you're register for a notification called CBDisplaySleep, so I'm a little confused. If the user turns the display off, it disappears from the system. You'd need to monitor for changes in the IORegistry topology to see that.

Thank you for replying to my post,

I guess I haven't give enough details.. the use case scenario is with my laptop with an external drive connected (for backups). What I want to achieve is an automatic unmount of the connected drive for either of the following events: 1/ I close the lid or 2/ the screen is turned off . Thus, when I disconnect the drive (actually the hub) I don't have to care about unmounting the external drive. In reality, there is more (not cpu intensive) tasks to be done. But That's the idea..

About your hint, I will check if it can be done.. but I guess you were thinking about an external display. In this case it makes sense that the display will disappear from the system. I don't think my laptop screen will do.

What I don't understand, is that the code above (the same as sleepwatcher of Bernhard Baehr (https://www.bernhard-baehr.de/) doesn't work as expected.. I mean, the display is clearly off, still the callback is never called (whatever the message). To turn off the screen I just use a display corner shortcut set to "set monitor to sleep".