1

I'm trying to simulate a keypress by clicking a button on my app. I've scoured stackoverflow and there are a few examples, but none of them seem to work for me. I can see the print statement in the console, but no character is pressed when I switch to a text editor. Here is what I have:

@IBAction func buttonClicked(_ sender: Any) {
    // Set delay to allow me to switch to a text editor
    let when = DispatchTime.now() + 2
    DispatchQueue.main.asyncAfter(deadline: when) {
        print("pressing keyboard button")
        self.keyboardKeyDown(key: 6)
        self.keyboardKeyUp(key: 6)
    }
}

func keyboardKeyDown(key: CGKeyCode) {
    let source = CGEventSource(stateID: .hidSystemState)
    let event = CGEvent(keyboardEventSource: source, virtualKey: key, keyDown: true)
    event?.post(tap: .cghidEventTap)
}

func keyboardKeyUp(key: CGKeyCode) {
    let source = CGEventSource(stateID: .hidSystemState)
    let event = CGEvent(keyboardEventSource: source, virtualKey: key, keyDown: false)
    event?.post(tap: .cghidEventTap)
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
Peter Devlin
  • 151
  • 1
  • 2
  • 12
  • 1
    Switch off sandboxing. – Willeke Nov 27 '17 at 18:07
  • Thanks Wileke, that worked. If you pop it in an answer I'll select it. – Peter Devlin Nov 28 '17 at 01:56
  • Here's a very good answer: [How to post a Quartz Event after Swift application launch?](https://stackoverflow.com/a/47213929/4244136). – Willeke Nov 29 '17 at 09:55
  • tFound this SO answer. Seems pretty similar to what you've done https://stackoverflow.com/questions/27484330/simulate-keypress-using-swift Did you try to open a text field inside the app, to see if the keypress is received here. – claude31 Nov 27 '17 at 09:51
  • So I can't simulate keypress if I have sandboxing on? Is there really no other way? Because without sandboxing, app will not pass Apple Review stage. – Starwave Jan 21 '20 at 23:38

0 Answers0