Search code examples
swiftmacos-mojavekeystroke

Unable to simulate keystrokes in macOS Mojave app


I need to simulate user keyboard input (e.g., typing the letter 'a') in a macOS Mojave app (Xcode 10.3). I'm trying to use the code posted in this question:

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

However, after my app requests permission to control System Events and I run the block of code below, nothing happens (aside from a statement printing that lets me know the block of code is actually being executed). The code runs without any errors, but I get no functionality.

I've made sure my app is not sandboxed, and my app has permission to control my computer and to control System Events (in security and privacy).

Here is the code I am using (99% of it came from the post linked above):

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)

Any ideas why this isn't working for me?


Solution

    1. You need to add "Privacy - AppleEvents Sending Usage Description" in info.plist

    2. Whenever you make any changes to your code you have to again disable and enable the permission of your app on security and privacy -> Accessibility