【问题标题】:Xcode Project Setting for CGEventTap?CGEventTap 的 Xcode 项目设置?
【发布时间】:2018-02-19 05:01:09
【问题描述】:

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

}

【问题讨论】:

    标签: swift xcode cocoa cgeventtap


    【解决方案1】:

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

    猜你喜欢
    • 2010-12-11
    • 1970-01-01
    • 2017-01-30
    • 1970-01-01
    • 1970-01-01
    • 2014-08-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-06
    相关资源
    最近更新 更多