Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically change Mac display brightness

How to change Mac display brightness from cocoa application?

like image 955
tig Avatar asked Jul 13 '10 17:07

tig


People also ask

How does Mac automatically adjust brightness?

Some MacBooks are equipped with ambient light sensors, and will attempt to automatically adjust the screen brightness to compensate for changes in surrounding light.

How do I increase the brightness on my Mac even more?

On your Mac, choose Apple menu > System Preferences, then click Displays . Drag the Brightness slider to adjust the brightness of your display.

How do I control screen brightness with software Mac?

In >System Preferences > Displays >Arrangement tab - drag the white bar at the top of your primary display over to the external monitor. You can then adjust the brightness on the external display using sliders or keyboard brightness keys.


1 Answers

CGDisplayIOServicePort is deprecated in OS 10.9 – so you have to use IOServiceGetMatchingServices to get the service parameter for IODisplaySetFloatParameter. Here's a basic function that looks for services named "display" and changes their brightness.

- (void) setBrightnessTo: (float) level
{

    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))) {
            IODisplaySetFloatParameter(service, kNilOptions, CFSTR(kIODisplayBrightnessKey), level);

            // Let the object go
            IOObjectRelease(service);

            return;
        }
    }
}

And in Swift (via @Dov):

private func setBrightnessLevel(level: Float) {
    var iterator: io_iterator_t = 0

    let result = IOServiceGetMatchingServices(kIOMasterPortDefault,
                                              IOServiceMatching("IODisplayConnect").takeUnretainedValue(),
                                              &iterator)

    if result == kIOReturnSuccess {
        var service: io_object_t = 1

        for ;; {
            service = IOIteratorNext(iterator)

            if service == 0 {
                break
            }

            IODisplaySetFloatParameter(service, 0, kIODisplayBrightnessKey, level)
            IOObjectRelease(service)
        }
    }
}

(code is open source of course)

like image 99
Alex King Avatar answered Oct 12 '22 16:10

Alex King