I'm searching for a way to simulate keystrokes in OSX. I found another solution (Simulate keypress for system wide hotkeys) using Objective-C, but i need to do it with Swift. How can i adapt CGEventCreateKeyboardEvent?
Swift 3
For me the hexadecimal key values like: 0x124 didn't work, but simple UInt 124 did the trick!
A nice collection of keycodes can be found here! This copy-paste code snippet simulates a right arrow keypress. Change the key number for whatever you want to simulate:
// Simulate Right Arrow keypress
let rightArrowKeyCode: UInt16 = 124
let keyDownEvent = CGEvent(keyboardEventSource: nil, virtualKey: rightArrowKeyCode, keyDown: true)
keyDownEvent?.flags = CGEventFlags.maskCommand
keyDownEvent?.post(tap: CGEventTapLocation.cghidEventTap)
let keyUpEvent = CGEvent(keyboardEventSource: nil, virtualKey: rightArrowKeyCode, keyDown: false)
keyUpEvent?.flags = CGEventFlags.maskCommand
keyUpEvent?.post(tap: CGEventTapLocation.cghidEventTap)
Update: For macOS Mojave and above you should allow your app to control your computer in System Preferences > Security & Privacy > Accessibility
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With