1

I am using event monitor to detect the key press event in swift. However, event monitor doesn't seem to detect command key or any other modifier key (shift, tab, opt ...) press. Is there a different way to detect modifier key press?. Note that I am not looking for a way to detect key combinations (ex: cmd+r) which can be done by using event.modifierFlags, but a way to know when command key alone is pressed.

override func viewDidLoad() {
        super.viewDidLoad()
        NSEvent.addLocalMonitorForEvents(matching: .keyDown, handler: commandKey(evt:))
}

    func commandKey(evt: NSEvent) -> NSEvent{
        if evt.keyCode == 55 { //key code for command is 55
          print("commanded")
        }
        return evt
    }

unknown
  • 407
  • 4
  • 11
  • 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 Mar 03 '21 at 20:00

1 Answers1

1

Found a solution. Seems .flagsChanged event is used to detect modifier key press.

override func viewDidLoad() {
        super.viewDidLoad()
        NSEvent.addLocalMonitorForEvents(matching: .flagsChanged, handler: commandKey(evt:))
}

func commandKey(evt: NSEvent) -> NSEvent{
        if evt.modifierFlags.contains(.command){
            print("commanded")
        }
        return evt
}
unknown
  • 407
  • 4
  • 11
  • 1
    The modifier keys (command, shift, option, control) are not considered keys in their own right. they change the interpretation of the other keys on the keyboard. Monitoring flag changes is the right way to do this. – Duncan C Mar 03 '21 at 17:57