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)
}