Swift:将击键转发到另一个过程 [英] Swift: forward keystrokes to a different process

查看:109
本文介绍了Swift:将击键转发到另一个过程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个应用程序,该应用程序使用其processID将其TextField之一上的按键转发到另一个进程.

I am trying to write an application that forwards the keypresses on one of its TextFields to a different process using its processID.

我得到的代码(如下)在侦听按键(现在是所有按键)方面效果很好,但是麻烦来自于将事件(keyDown/keyUp)转发到另一个进程.

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.

我尝试过的事情:

  1. CGEvent.postToPid:不起作用(什么都没有发送给其他进程)
  2. CGEvent.postToPSN:无法正常运行,因为它需要进程序列号作为UnsafeMutableRawPointer(不是我首先知道如何获取PSN)
  3. 手动创建CGEvent,然后尝试1.和2.
  4. 阅读有关类及其功能的文档(它们似乎并不那么流行)
  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)

任何帮助将不胜感激.

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

推荐答案

其中一项评论表明,权限可能是原因,而实际上是原因.

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.

请记住,应用程序沙箱是您的应用程序在App Store上的要求(

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

这篇关于Swift:将击键转发到另一个过程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆