Skip to content

Instantly share code, notes, and snippets.

@andermoran
Last active August 30, 2023 05:23
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andermoran/2195a4ecd4f212cbd2c36afba1f58cdb to your computer and use it in GitHub Desktop.
Save andermoran/2195a4ecd4f212cbd2c36afba1f58cdb to your computer and use it in GitHub Desktop.
Programmatically read and change the brightness on macOS
#import <Foundation/Foundation.h>
#import <IOKit/IOKitLib.h>
#import <IOKit/graphics/IOGraphicsLib.h>
// this helped me out a lot <3: https://stackoverflow.com/questions/3239749/programmatically-change-mac-display-brightness
int main(int argc, char *argv[]) {
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))) {
// Print the current brightness of the screen
float current_brightness;
IODisplayGetFloatParameter(service, kNilOptions, CFSTR(kIODisplayBrightnessKey), &current_brightness);
printf("current brightness: %.0f%%\n", current_brightness * 100);
// Set the custom brightness of the screen
float custom_brightness = 0.69; /* this value controls the screen brightness with
0 being minimum brightness and 1 being maximum brightness */
IODisplaySetFloatParameter(service, kNilOptions, CFSTR(kIODisplayBrightnessKey), custom_brightness);
// Print the custom brightness of the screen
IODisplayGetFloatParameter(service, kNilOptions, CFSTR(kIODisplayBrightnessKey),
&custom_brightness);
printf("new custom brightness: %.0f%%\n", custom_brightness * 100);
// Let the object go
IOObjectRelease(service);
return 0;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment