Duelsol
Duelsol

Reputation: 139

Swift2: CGEventSetFlags with multi CGEventFlags

I'm trying to trigger a shortcut keys such as ctrl+cmd+space

At first my code is like this:

let source = CGEventSourceCreate(.CombinedSessionState)
let keyDown = CGEventCreateKeyboardEvent(source, 49 as CGKeyCode, true)
let keyUp = CGEventCreateKeyboardEvent(source, 49 as CGKeyCode, false)
CGEventSetFlags(keyDown, .MaskCommand)
CGEventSetFlags(keyDown, .MaskControl)
CGEventPost(.CGSessionEventTap, keyDown)
CGEventPost(.CGSessionEventTap, keyUp)

But it doesn't work because .MaskControl has overwriting .MaskCommand which means I need to use method CGEventSetFlags only once and set both command key and control key.

So I google it and find that you can do like this in Swift1: CGEventSetFlags(keyDown, .MaskCommand | .MaskControl). Does it right? Well, I'm use Swift2 and it's not work. And I tried CGEventSetFlags(keyDown, [.MaskCommand, .MaskControl]), also not work.

So, please tell me the right way to use CGEventSetFlags in Swift2. Thanks!

Upvotes: 3

Views: 666

Answers (1)

vadian
vadian

Reputation: 285140

"Or" the raw values and create a new CGEventFlags item

let commandControlMask = (CGEventFlags.maskCommand.rawValue | CGEventFlags.maskControl.rawValue)
let commandControlMaskFlags = CGEventFlags(rawValue: commandControlMask)
CGEventSetFlags(keyDown, commandControlMaskFlags)

Upvotes: 4

Related Questions