Adjust screen brightness in Mac OS X app

拈花ヽ惹草 提交于 2019-11-30 17:53:19

问题


I want to control the brightness of the main-screen within my Mac OS X app (like the F1/F2 buttons). In iOS, there's something like this:

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

In OSX we have NSScreen, which is nice to find out what the main-screen is, but it misses the .brightness method.

So how can I adjust the monitor brightness using Swift on OSX?


回答1:


There's no such nice API for doing this on OS X.

We have to use IOServiceGetMatchingServices to find "IODisplayConnect" (the display device) then use the kIODisplayBrightnessKey to set 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)


来源:https://stackoverflow.com/questions/32691397/adjust-screen-brightness-in-mac-os-x-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!