How to detect Caps Lock status on macOS with Swift without a window?

淺唱寂寞╮ 提交于 2020-03-05 04:33:53

问题


I have tried KeyDown and NSEvent, but they require a NSWindow object to be active. My hope is that I can put an app on the status bar and alert the user when it has pressed CapsLock, even if the user is in any other app. My app idea doesn't have a window for settings or anything else, is just an indicator. Can it even be done? I am guessing the AppDelegate but can't figure out how to make it receive modifier events. Any help really appreciated!

I have looked on stack overflow for a "duplicate" but no one has ever asked this question as far as I searched.


回答1:


You just need to monitor the NSEvent modifier flags changed for capslock. The easiest way is to create a method that takes a NSEvent and check if the modifierFlags property intersection with .deviceIndependentFlagsMask contains .capsLock:

func isCapslockEnabled(with event: NSEvent) -> Bool {
    event.modifierFlags.intersection(.deviceIndependentFlagsMask).contains(.capsLock)
}

Now you just need to add global monitoring event to your applicationDidFinishLaunching method:

func applicationDidFinishLaunching(_ aNotification: Notification) {
    NSEvent.addGlobalMonitorForEvents(matching: .flagsChanged, handler: flagsChanged)
}

And create a method to deal with the event of flagsChanged:

func flagsChanged(with event: NSEvent) {
    print("Capslock is Enabled:", isCapslockEnabled(with: event))
}


来源:https://stackoverflow.com/questions/59590699/how-to-detect-caps-lock-status-on-macos-with-swift-without-a-window

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