2

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:

  1. CGEvent.postToPid: Does not work (nothing sent to the other process)
  2. 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)
  3. Manually creating the CGEvent and then trying 1. and 2.
  4. 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)
  }
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
fort08
  • 21
  • 3
  • This isn't really a Swift question. It's a macOS / Cocoa question. Also, I think your posting app needs to be added to the list of Accessibility apps in the Privacy tab of the Security & Privacy system preference pane. Have you done that? – rob mayoff Nov 29 '17 at 19:30
  • Is the other process your process too? What's the exact situation here? – matt Nov 29 '17 at 19:43
  • @robmayoff Thanks for the suggestion. Turns out the App Sandboxing had to be disabled (enabled by default) in the Capabilities section of the Xcode project. I can now forward the keypresses. – fort08 Nov 29 '17 at 19:48

1 Answers1

0

One of the comments suggested that permissions might be the cause, and it was.

My problem was resolved by going to the Capabilities section of my project and disabling App Sandboxing, which was enabled by default.

Keep in mind that App Sandboxing is a requirement for your app to be on the App Store (reference)

fort08
  • 21
  • 3