繁体   English   中英

CGEventTap 的 Xcode 项目设置?

[英]Xcode Project Setting for CGEventTap?

不久前,我创建了一个非常简单的 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
    }

}

答案是从功能中取消选中 Sandbox。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM