次のコードで実現できます
import IOKit
import IOKit.hid
func SetCapslockState(_ enabled: Bool) {
guard let serviceDictionary = IOServiceMatching(kIOHIDSystemClass) else { return }
let ioService = IOServiceGetMatchingService(kIOMainPortDefault, serviceDictionary)
if ioService == MACH_PORT_NULL { return }
var ioConnection: io_connect_t = 0
let result = IOServiceOpen(ioService, mach_task_self_, UInt32(kIOHIDParamConnectType), &ioConnection)
IOObjectRelease(ioService)
if result == KERN_SUCCESS {
IOHIDSetModifierLockState(ioConnection, Int32(kIOHIDCapsLockState), enabled)
IOServiceClose(ioConnection)
}
}
func GetCapslockState() -> Bool {
guard let serviceDictionary = IOServiceMatching(kIOHIDSystemClass) else { return false }
let ioService = IOServiceGetMatchingService(kIOMainPortDefault, serviceDictionary)
if ioService == MACH_PORT_NULL { return false }
var state = false
var ioConnection: io_connect_t = 0
let result = IOServiceOpen(ioService, mach_task_self_, UInt32(kIOHIDParamConnectType), &ioConnection)
IOObjectRelease(ioService)
if result == KERN_SUCCESS {
IOHIDGetModifierLockState(ioConnection, Int32(kIOHIDCapsLockState), &state)
IOServiceClose(ioConnection)
}
return state
}
使い方
CapsLock状態を設定する
//連動して実キーボードのCapsLockを示すLEDがOn/Offします
SetCapslockState(true) //CapsLockをOnにする
SetCapslockState(false) //CapsLockをOffにする
CapsLock状態を取得する
let capsLockState = GetCapslockState()
//true :CapsLock On状態
//fasle:CapsLock Off状態
macOS Sonoma 14.7.2 (23H311)
,swift-driver version: 1.90.11.1 Apple Swift version 5.10 (swiftlang-5.10.0.13 clang-1500.3.9.4)
および
macOS Sequoia 15.3.1 (24D70)
,swift-driver version: 1.115.1 Apple Swift version 6.0.3 (swiftlang-6.0.3.1.10 clang-1600.0.30.1)
で動作確認済み。
Swift Repl でも可。
以上