0

On CMD keypress, this func:

override func keyDown(with event: NSEvent) {
    super.keyDown(with: event)
        
    let flags = event.modifierFlags
    print(flags)
    print(NSEvent.ModifierFlags.command.rawValue)
}

returns:

NSEventModifierFlags(rawValue: 1048848)
1048576

Why are the raw values not equivalent? flags == .command returns false on a command key press because of the inequivalent raw values.

Xcode 12.5, OSX 11.2.2

Iskeraet
  • 731
  • 1
  • 6
  • 12
  • 2
    It's a bitmask. You cannot use `==` to check for anything. Use `.contains`. (And don't think about the raw value.) – matt May 09 '21 at 02:45
  • Funny enough, I made a little debug tool to inspect keyboard NSEvents recently. I uploaded it so you can take a look it. It'll show you all the different parts that go into the modifierFlags bit field. But really, you should just use `.contains`, as matt said. https://gitlab.com/AMomchilov/public/experiments/keyboard-nsevent-inspector/-/blob/main/KeyDetectionDemo/ViewController.swift#L67-101 – Alexander May 10 '21 at 20:44
  • I think the exact set of values you're seeing is: `(cmdKey << 12) | keyUpMask | activMask` (expressed using the constants in [`HIToolbox/Events.h`](https://github.com/phracker/MacOSX-SDKs/blob/master/MacOSX10.6.sdk/System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/HIToolbox.framework/Versions/A/Headers/Events.h)) – Alexander May 10 '21 at 20:57
  • Use ```let flags = event.modifierFlags.intersection(.deviceIndependentFlagsMask)``` – scchn Aug 10 '21 at 03:18

0 Answers0