Keyboard event(CGEvent)'s flags is not correct

Viewed 186

I'm working on an app which encoding input characters into another language (Vietnamese) and I've facing with some issue of Apple documentation.

My code to listen for keyboard events is:

func cgEventCallback (
    proxy: CGEventTapProxy,
    type: CGEventType,
    event: CGEvent,
    refcon: UnsafeMutableRawPointer?
) -> Unmanaged<CGEvent>? {
    switch type {
    case .keyDown:
        print(event.flags, CGEventFlags.maskCommand)

        if (event.flags == CGEventFlags.maskCommand) {
            print("Flag is Command")
        } else {
            print("Flag is not Command")
        }

    default:
        break
    }

    return Unmanaged.passRetained(event)
}

As they said, CGEvent's flags returns the event flags of a Quartz event. So I expect that when I type in Command + C then it should print out:

CGEventFlags(rawValue: 1048576) CGEventFlags(rawValue: 1048576)
Flag is Command

But the issue is that the printed out text is not the same as expected:

CGEventFlags(rawValue: 1048840) CGEventFlags(rawValue: 1048576)
Flag is not Command

Am I misunderstanding about something or is there any way which could help me know what is the current flag of the event?

1 Answers

event.flags is an OptionSet representing all flags for the current event. There can be more than one flag set, and that is what is happening in your case:

event.flags  = 1048840 (decimal) = 100108 (hex)
.maskCommand = 1048576 (decimal) = 100000 (hex)

So the correct test is

if event.flags.contains(.maskCommand) { ... }

instead of testing for equality.

Related