1

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.

Lew Winczynski
  • 1,190
  • 1
  • 11
  • 20
Ryuuzaki Julio
  • 369
  • 1
  • 14
  • Does this answer your question? [Global modifier key press detection in Swift](https://stackoverflow.com/questions/41927843/global-modifier-key-press-detection-in-swift) – Willeke Jan 04 '20 at 13:58

1 Answers1

4

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))
}
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
  • 3
    how would you check to see if caps lock is down upon launch? I.E. what if the event occurred BEFORE launch like KeyMap long ago – Roy Lovejoy Dec 08 '20 at 20:18