lswank
lswank

Reputation: 2471

Get Display Brightness

Is there a way to get the display brightness in OS X 10.9+ now that CGDisplayIOServicePort has been deprecated?

Upvotes: 1

Views: 1102

Answers (3)

Avi Rok
Avi Rok

Reputation: 558

Ok I get brightness level of Apple Silicone (tested on M1 Pro) by using private framework DisplayServices.framework extern int DisplayServicesGetBrightness(CGDirectDisplayID display, float *brightness); you just need to find the DisplayServices header file

*I'm not tested it with external display yet

func getDisplayBrightnessM1() -> Float {
var brightness: Float = 0.0
DisplayServicesGetBrightness(1, &brightness)
return brightness
}

Upvotes: 0

Tobias
Tobias

Reputation: 947

If you are using swift the following should work:

func getDisplayBrightness() -> Float {

    var brightness: Float = 1.0
    var service: io_object_t = 1
    var iterator: io_iterator_t = 0
    let result: kern_return_t = IOServiceGetMatchingServices(kIOMasterPortDefault, IOServiceMatching("IODisplayConnect"), &iterator)

    if result == kIOReturnSuccess {

        while service != 0 {
            service = IOIteratorNext(iterator)
            IODisplayGetFloatParameter(service, 0, kIODisplayBrightnessKey as CFString, &brightness)
            IOObjectRelease(service)
        }
    }
    return brightness
}

Upvotes: 0

lswank
lswank

Reputation: 2471

After some searching and fiddling around, here is a "future proof" way to get the brightness of the display that doesn't use the CGDisplayIOServicePort deprecated in OS X 10.9.

- (float)getDisplayBrightness
{
    float brightness = 1.0f;
    io_iterator_t iterator;
    kern_return_t result = 
        IOServiceGetMatchingServices(kIOMasterPortDefault,
            IOServiceMatching("IODisplayConnect"),
            &iterator);

    // If we were successful
    if (result == kIOReturnSuccess)
    {
        io_object_t service;

        while ((service = IOIteratorNext(iterator)))
        {
            IODisplayGetFloatParameter(service, 
                kNilOptions, 
                CFSTR(kIODisplayBrightnessKey), 
                &brightness);

            // Let the object go
            IOObjectRelease(service);
        }
    }

    return brightness;
}

Upvotes: 6

Related Questions