Duelsol February 2016

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!

Answers


vadian February 2016

"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)

Post Status

Asked in February 2016
Viewed 1,800 times
Voted 10
Answered 1 times

Search




Leave an answer