如何从可可应用程序更改 Mac 显示亮度?
问问题
7133 次
4 回答
15
CGDisplayIOServicePort
在 OS 10.9 中已弃用-因此您必须使用IOServiceGetMatchingServices
来获取IODisplaySetFloatParameter
. 这是一个查找名为“显示”的服务并更改其亮度的基本功能。
- (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;
}
}
}
在 Swift 中(通过@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)
}
}
}
(代码当然是开源的)
于 2014-02-09T03:53:46.777 回答
6
扩展亚历克斯的答案:
在带有 Swift3 的 Xcode8 beta3 中,代码更加精简。
private func setBrightness(level: Float) {
let service = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("IODisplayConnect"))
IODisplaySetFloatParameter(service, 0, kIODisplayBrightnessKey, level)
IOObjectRelease(service)
}
于 2016-07-29T22:33:11.917 回答
3
来自 Alec Jacobson 的亮度菜单源代码:
- (void) set_brightness:(float) new_brightness {
CGDirectDisplayID display[kMaxDisplays];
CGDisplayCount numDisplays;
CGDisplayErr err;
err = CGGetActiveDisplayList(kMaxDisplays, display, &numDisplays);
if (err != CGDisplayNoErr)
printf("cannot get list of displays (error %d)\n",err);
for (CGDisplayCount i = 0; i < numDisplays; ++i) {
CGDirectDisplayID dspy = display[i];
CFDictionaryRef originalMode = CGDisplayCurrentMode(dspy);
if (originalMode == NULL)
continue;
io_service_t service = CGDisplayIOServicePort(dspy);
float brightness;
err= IODisplayGetFloatParameter(service, kNilOptions, kDisplayBrightness,
&brightness);
if (err != kIOReturnSuccess) {
fprintf(stderr,
"failed to get brightness of display 0x%x (error %d)",
(unsigned int)dspy, err);
continue;
}
err = IODisplaySetFloatParameter(service, kNilOptions, kDisplayBrightness,
new_brightness);
if (err != kIOReturnSuccess) {
fprintf(stderr,
"Failed to set brightness of display 0x%x (error %d)",
(unsigned int)dspy, err);
continue;
}
}
}
于 2011-01-05T10:21:37.150 回答
2
在 Xcode 8 beta 6 中无法编译:
IODisplaySetFloatParameter(service, 0, kIODisplayBrightnessKey, level)
无法将“String”类型的值转换为预期的参数类型“CFString!”
所以让我们投吧:
IODisplaySetFloatParameter(service, 0, kIODisplayBrightnessKey as CFString!, level)
于 2016-08-16T20:22:52.680 回答