Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
801 views
in Technique[技术] by (71.8m points)

cocoa - Programmatically change Mac display brightness

How to change Mac display brightness from cocoa application?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...