Simulate keystrokes with Quartz events in macOS Sierra

℡╲_俬逩灬. 提交于 2019-12-11 05:29:59

问题


I am simulating keystrokes in macOS, and sending them to the active application. I am doing it along the lines of https://stackoverflow.com/a/27487493/5600424 but in Swift 3. For example, to send an 'a':

let eventSource = CGEventSource(stateID: CGEventSourceStateID.hidSystemState)
let key: CGKeyCode = 0     // virtual key for 'a'
let eventDown = CGEvent(keyboardEventSource: eventSource, virtualKey: key, keyDown: true)
let eventUp = CGEvent(keyboardEventSource: eventSource, virtualKey: key, keyDown: false)
let location = CGEventTapLocation.cghidEventTap
eventDown.post(tap: location)
eventUp.post(tap: location)

This was working fine on OSX El Capitan (Swift 3, Xcode 8.0), but it stopped working after updating to macOs Sierra. The application itself still receives the keystroke when it's active, however when a different application is active the events seem lost. I have tried to figure out what is happening without success, and the documentation does not help. Any help would be appreciated, thanks!


回答1:


The code quoted in the question works correctly, and its behavior has not changed when upgrading from El Capitan to Sierra, contrary to what claimed.

The keystrokes where not received by other applications because once the application was in the background, the function responsible for sending the keyboard events with the above code was not called anymore, for independent reasons.



来源:https://stackoverflow.com/questions/39647443/simulate-keystrokes-with-quartz-events-in-macos-sierra

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