Last active
December 19, 2024 04:09
-
-
Save andermoran/2195a4ecd4f212cbd2c36afba1f58cdb to your computer and use it in GitHub Desktop.
Programmatically read and change the brightness on macOS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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), ¤t_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