Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cocoa: Simulating Command+Tab in CGEvent

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!

like image 474
Duelsol Avatar asked Apr 02 '16 15:04

Duelsol


1 Answers

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

like image 118
Willeke Avatar answered Sep 19 '22 10:09

Willeke