I am trying to write an application that forwards the keypresses on one of its TextFields to a different process using its processID.
The code (below) that I have got works well in terms of listening to the key presses (right now, all key presses), but the trouble is coming from forwarding the events (keyDown/keyUp) to the other process.
Things I have tried:
CGEvent.postToPid
: Does not work (nothing sent to the other process)CGEvent.postToPSN
: Could not get it to work as it requires the Process Serial Number as an UnsafeMutableRawPointer (not that I know how to get the PSN is in the first place)- Manually creating the CGEvent and then trying 1. and 2.
- Reading documentation on the classes and their functions (they don't seem to be that popular)
Any help would be greatly appreciated.
import Cocoa
class ViewController: NSViewController {
var pid: Int32 = 12345
override func viewDidLoad() {
super.viewDidLoad()
NSEvent.addLocalMonitorForEvents(matching: .keyDown) {
(event) -> NSEvent? in
self.keyDown(with: event)
return event
}
// For some reason, keyUp is triggered twice
NSEvent.addLocalMonitorForEvents(matching: .keyUp) {
(event) -> NSEvent? in
self.keyUp(with: event)
return event
}
}
override func keyDown(with event: NSEvent) {
print("Down " + String(event.keyCode))
var cgEvent = event.cgEvent
cgEvent?.postToPid(pid)
}
override func keyUp(with event: NSEvent) {
print("Up " + String(event.keyCode))
var cgEvent = event.cgEvent
cgEvent?.postToPid(pid)
}
}