0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[Mac] CapsLock を Swift で ON/OFF する方法

Posted at

次のコードで実現できます

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 でも可。

 

以上

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?