Adjust screen brightness in Mac OS X

I want to control the brightness of the main screen in a Mac OS X application (e.g. F1 / F2 buttons). There is something like this in iOS:

UIScreen.mainScreen().brightness = CGFloat(0.5)

In OSX, we have NSScreen, which is nice to know what the main screen is, but it skips the method .brightness.

So how to adjust monitor brightness using Swift on OSX?

+4
source share
1 answer

There is no such nice API for this in OS X.

We must use IOServiceGetMatchingServicesto find "IODisplayConnect"(display device), then use to kIODisplayBrightnessKeyset the brightness:

func setBrightnessLevel(level: Float) {

    var iterator: io_iterator_t = 0

    if IOServiceGetMatchingServices(kIOMasterPortDefault, IOServiceMatching("IODisplayConnect"), &iterator) == kIOReturnSuccess {

        var service: io_object_t = 1

        while service != 0 {

            service = IOIteratorNext(iterator)
            IODisplaySetFloatParameter(service, 0, kIODisplayBrightnessKey, level)
            IOObjectRelease(service)

        }

    }
}

setBrightnessLevel(0.5)
+10
source

Source: https://habr.com/ru/post/1608287/


All Articles