在控制台应用程序中使用swift处理可可键事件(按下键)

and*_*llo 10 macos cocoa swift

好的,所以我正在尝试登录控制台输出按下了哪些键.我无法理解可可结构,既不是Obj-c,也不是swift.我不是这两种语言的大师,但......这里是我的代码:

import Cocoa
import Foundation
import AppKit

var loop = true
var idRegisterdEvent: AnyObject? = nil

func handlerEvent(myEvent: (NSEvent!)) -> Void {
    print(myEvent.keyCode)
}

while loop {

    idRegisterdEvent = NSEvent.addGlobalMonitorForEventsMatchingMask(NSEventMask.KeyDownMask, handler: handlerEvent)
}
Run Code Online (Sandbox Code Playgroud)

我知道一切都是错的,是的..但男人,这些事件,我无法理解它们是如何运作的.

Mar*_*kov 12

在谷歌上花了几个小时后,我最终阅读了几个github资源.事实证明,有人已经弄明白了.

基本上你需要创建一个NSApplicationDelegate,让你的应用程序能够收听系统事件.

以下显示了所需的最小代码(swift2):

func acquirePrivileges() -> Bool {
    let accessEnabled = AXIsProcessTrustedWithOptions(
        [kAXTrustedCheckOptionPrompt.takeUnretainedValue() as String: true])

    if accessEnabled != true {
        print("You need to enable the keylogger in the System Preferences")
    }
    return accessEnabled == true
}

class ApplicationDelegate: NSObject, NSApplicationDelegate {
    func applicationDidFinishLaunching(notification: NSNotification?) {

        acquirePrivileges()
        // keyboard listeners
        NSEvent.addGlobalMonitorForEventsMatchingMask(
            NSEventMask.KeyDownMask, handler: {(event: NSEvent) in
                print(event)
        })
    }
}

// preparing main loop
let application = NSApplication.sharedApplication()
let applicationDelegate = MyObserver()
application.delegate = applicationDelegate
application.activateIgnoringOtherApps(true)
application.run()
Run Code Online (Sandbox Code Playgroud)

如果您只对捕获非可访问性事件感兴趣(例如:),NSWorkspaceDidActivateApplicationNotification那么您可以使用更少的代码行来获取所需的代码NSRunLoop.mainRunLoop().run().我只添加了这个例子,因为我看到了你的while true 事件循环,它永远不会让你听任何系统事件,因为它阻塞了主线程.

class MyObserver: NSObject
{
    override init() {
        super.init()

        // app listeners
        NSWorkspace.sharedWorkspace().notificationCenter.addObserver(self, selector: "SwitchedApp:", name: NSWorkspaceDidActivateApplicationNotification, object: nil)
    }

    func SwitchedApp(notification: NSNotification!)
    {
        print(notification)    
    }
}


let observer = MyObserver()

// simply to keep the command line tool alive - as a daemon process
NSRunLoop.mainRunLoop().run()
Run Code Online (Sandbox Code Playgroud)