Cocoa: Simulating Command+Tab in CGEvent

懵懂的女人 提交于 2019-12-10 13:55:43

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!