Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simulate keypress using Swift

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?

like image 802
ixany Avatar asked Dec 15 '14 12:12

ixany


1 Answers

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

like image 175
balazs630 Avatar answered Oct 01 '22 19:10

balazs630