问题
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!
回答1:
The Command flag is missing in the keyup event. Add CGEventSetFlags(keyUp, .MaskCommand)
before CGEventPost(.CGHIDEventTap, keyUp)
.
来源:https://stackoverflow.com/questions/36375080/cocoa-simulating-commandtab-in-cgevent