I want to simulate Application Switcher in my app and I think CGEvent maybe can do that.
Well, after learning some basic information about CGEvent, I can simulate the key press Command + Tab. But the Application Switcher window just flashing by and switch to another app immediately.
I realize that I need to hold the Command key and press Tab key to choose the app. So, here's my code:
// Hold the Command key
let source = CGEventSourceCreate(.HIDSystemState)
let event = CGEventCreateKeyboardEvent(source, 55 as CGKeyCode, true)
CGEventSetIntegerValueField(event, .KeyboardEventAutorepeat, 1)
CGEventPost(.CGHIDEventTap, event)
// Press Tab key once
let source = CGEventSourceCreate(.HIDSystemState)
let keyDown = CGEventCreateKeyboardEvent(source, 48 as CGKeyCode, true)
CGEventSetFlags(keyDown, .MaskCommand)
CGEventPost(.CGHIDEventTap, keyDown)
let keyUp = CGEventCreateKeyboardEvent(source, 48 as CGKeyCode, false)
CGEventPost(.CGHIDEventTap, keyUp)
But it doesn't work! Any ideas? Thanks!
The Command flag is missing in the keyup event. Add CGEventSetFlags(keyUp, .MaskCommand) before CGEventPost(.CGHIDEventTap, keyUp).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With