Tza*_*zar 11 hardware macos iokit swift
\xe2\x80\x99s 很容易检测 Mac 是否有发光键盘ioreg在命令行中,
ioreg -c IOResources -d 3 | grep '"KeyboardBacklight" =' | sed 's/^.*= //g'\nRun Code Online (Sandbox Code Playgroud)\n但我怎样才能以编程方式得到这个IOKit使用最新的 Swift 以编程方式获取这个布尔属性呢?我\xe2\x80\x99m 寻找一些示例代码。
我通过一些尝试和错误发现了以下内容:
我已经在 MacBook Air(带键盘背光)和 iMac(不带键盘背光)上进行了测试,在两种情况下都产生了正确的结果。
import Foundation
import IOKit
func keyboardHasBacklight() -> Bool {
let port: mach_port_t
if #available(macOS 12.0, *) {
port = kIOMainPortDefault // New name as of macOS 12
} else {
port = kIOMasterPortDefault // Old name up to macOS 11
}
let service = IOServiceGetMatchingService(port, IOServiceMatching(kIOResourcesClass))
guard service != IO_OBJECT_NULL else {
// Could not read IO registry node. You have to decide whether
// to treat this as a fatal error or not.
return false
}
guard let cfProp = IORegistryEntryCreateCFProperty(service, "KeyboardBacklight" as CFString,
kCFAllocatorDefault, 0)?.takeRetainedValue(),
let hasBacklight = cfProp as? Bool
else {
// "KeyboardBacklight" property not present, or not a boolean.
// This happens on Macs without keyboard backlight.
return false
}
// Successfully read boolean "KeyboardBacklight" property:
return hasBacklight
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
629 次 |
| 最近记录: |