How to change Mac display brightness from cocoa application?
Some MacBooks are equipped with ambient light sensors, and will attempt to automatically adjust the screen brightness to compensate for changes in surrounding light.
On your Mac, choose Apple menu > System Preferences, then click Displays . Drag the Brightness slider to adjust the brightness of your display.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With