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

2024-04-30

好吧,我正在尝试登录控制台输出按下的键。我只是无法理解可可的结构,无论是 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)
}

我知道一切都错了,是的……但是,伙计,这些事件,我无法理解它们是如何运作的。


在 google 上花了几个小时后,我最终阅读了一些 github 资源。事实证明有人已经弄清楚了 https://github.com/AntiHaus/SwiftLog/blob/8d5f6a10ff71920daf33522ec6547ecd2d5bcbc7/SwiftLog/main.swift.

基本上你需要创建一个NSApplicationDelegate,这使您的应用程序能够侦听系统事件。

下图显示了最低限度的代码 needed(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()

如果您只是对捕捉感兴趣不可访问性事件(例如: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()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐