Simulate sending key to an NSView on a macOS application

Hello,

I am trying to simulate a keystroke inside a macOS application.

Here is what i've done:

    let src = CGEventSource(stateID: CGEventSourceStateID.hidSystemState)
   let cmd_down = CGEvent(keyboardEventSource: src, virtualKey: 0x38, keyDown: true)
   let cmd_up = CGEvent(keyboardEventSource: src, virtualKey: 0x38, keyDown: false)
   cmd_down?.post(tap: .cghidEventTap)
   cmd_up?.post(tap: .cghidEventTap)

macOS is asking me to allow my application on TCC accessibility. This is a global privilege and needs admin rights. And i want to avoid that.

Is there an alternative to simulate a key stroke inside my application ?

Thanks

You could create an NSEvent and use the sendEvent method of NSApplication.

Afterthought: although -[NSApplication sendEvent:] seems to work OK for simulating keyboard events, it's probably preferable in general to use -[NSApplication postEvent:atStart:]. The latter works better for mouse events.

Simulate sending key to an NSView on a macOS application
 
 
Q