5

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!

Duelsol
  • 149
  • 9
  • When I type Command-tab manually, the Application Switcher window just flashes by and switches to another app immediately. – Willeke Apr 03 '16 at 11:51
  • Why do you set KeyboardEventAutorepeat? – Willeke Apr 03 '16 at 11:52
  • You have to simulate the user: Command down, tab down, tab up, command up. – Willeke Apr 03 '16 at 11:55
  • @Willeke It doesn't matter whether I add the code `CGEventSetIntegerValueField(event, .KeyboardEventAutorepeat, 1)` or not – Duelsol Apr 03 '16 at 12:36
  • @Willeke Maybe my expression was not accurate. I find this discussion: [How do I script the Application Switcher?](https://discussions.apple.com/thread/1928648?start=0&tstart=0) exactly had the same problem with me. – Duelsol Apr 03 '16 at 12:40
  • 1
    Sorry I didn't know I had to hold the Command key. Try `CGEventSetFlags(keyUp, .MaskCommand)` before `CGEventPost(.CGHIDEventTap, keyUp)`. – Willeke Apr 03 '16 at 14:30
  • @Willeke It works! Thanks man! I didn't realize that I also need to set flags when Key Up. Please answer this post and I will set it as the best answer. – Duelsol Apr 04 '16 at 08:09

1 Answers1

7

The Command flag is missing in the keyup event. Add CGEventSetFlags(keyUp, .MaskCommand) before CGEventPost(.CGHIDEventTap, keyUp).

Willeke
  • 14,578
  • 4
  • 19
  • 47
  • my apologies if this is poor from, but you seem to be expert in this area. I've just posted https://stackoverflow.com/questions/58673983/simulating-opt-or-other-modifiers-with-cgeventcreatekeyboardevent-cgeventse -- If you are able to offer any insight, I am most grateful! – P i Nov 02 '19 at 19:47