-1

前段时间,我创建了一个非常简单的 Xcode 项目来测试 CGEventTap,当我从 Xcode 运行时它工作得非常好。代码在底部。

但是,如果我在 Xcode 上创建一个新项目,粘贴下面完全相同的代码,然后从 Xcode 运行,我会得到“无法创建事件点击”。

为了让 CGEventTap 工作,我需要更改项目设置吗?我什至尝试将 info.plist 从旧测试项目复制并粘贴到新项目。

我很困惑。谢谢您的帮助!

// ViewController.swift
import Cocoa

class ViewController: NSViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        func myCGEventCallback(proxy : CGEventTapProxy, type : CGEventType, event : CGEvent, refcon : UnsafeMutableRawPointer?) -> Unmanaged<CGEvent>? {
            if type == .keyDown || type == .keyUp || type == .flagsChanged {
                let keyCode = event.getIntegerValueField(.keyboardEventKeycode)
                print(keyCode)
            }
            return Unmanaged.passRetained(event)
        }

        let eventMask = (1 << CGEventType.keyDown.rawValue) | (1 << CGEventType.keyUp.rawValue) | (1 << CGEventType.flagsChanged.rawValue)
        guard let eventTap = CGEvent.tapCreate(tap: .cgSessionEventTap, place: .headInsertEventTap, options: .defaultTap, eventsOfInterest: CGEventMask(eventMask), callback: myCGEventCallback, userInfo: nil) else {
            debugPrint("Failed to create event tap")
            exit(1)
        }
        let runLoopSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, eventTap, 0)
        CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, CFRunLoopMode.commonModes)
        CGEvent.tapEnable(tap: eventTap, enable: true)
    }

    override var representedObject: Any? {
        didSet {
            // Update the view, if already loaded.
        }
    }

}

// AppDelegate.swift
import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    func applicationDidFinishLaunching(_ aNotification: Notification) {
        // Insert code here to initialize your application
    }

    func applicationWillTerminate(_ aNotification: Notification) {
        // Insert code here to tear down your application
    }

}
4

1 回答 1

0

答案是从功能中取消选中沙盒。

于 2018-02-19T05:25:01.800 回答