问题
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