在控制台应用程序中使用swift处理可可键事件(按键) [英] Handling cocoa key events (keys pressed) with swift in a console application

查看:118
本文介绍了在控制台应用程序中使用swift处理可可键事件(按键)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,所以我试图登录控制台输出按什么键。我只是不能理解可可结构,既不与Obj-c,也不迅速。我不是这两种语言的主人,但...这里是我的代码:

  import Cocoa 
import基础
import AppKit

var loop = true
var idRegisterdEvent:AnyObject? = nil

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

while循环{

idRegisterdEvent = NSEvent.addGlobalMonitorForEventsMatchingMask(NSEventMask.KeyDownMask,handler:handlerEvent)
}

我知道一切都是错的,是啊,但是,

解决方案

在google上花了几个小时后,我最终读了几个github资源。事实证明,有人已经知道了。 p>

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



下面显示了最小代码 swift2 ):

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

如果accessEnabled!= true {
print在系统首选项中启用键盘记录器)
}
return accessEnabled == true
}

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

acquirePrivileges()
//键盘侦听器
NSEvent.addGlobalMonitorForEventsMatchingMask(
NSEventMask.KeyDownMask,handler:{(event:NSEvent) in
print(event)
})
}
}

//准备主循环
let application = NSApplication.sharedApplication
let applicationDelegate = MyObserver()
application.delegate = applicationDelegate
application.activateIgnoringOtherApps(true)
application.run()

如果你只想捕获不可访问性事件(例如: NSWorkspaceDidActivateApplicationNotification ),你可以用更少的代码行,因为你只需要 NSRunLoop.mainRunLoop()。run()。我只添加了这个例子,因为我看到你的而真实 event-loop ,从来不会让你监听任何系统事件,主线程。

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

//应用程序侦听器
NSWorkspace.sharedWorkspace()。notificationCenter.addObserver(self,selector:SwitchedApp:,name:NSWorkspaceDidActivateApplicationNotification,object:nil)
}

func SwitchedApp(notification:NSNotification!)
{
print(notification)
}
}
$ b b
let observer = MyObserver()

//简单地保持命令行工具活动 - 作为守护进程
NSRunLoop.mainRunLoop()。run()


Ok so i'm trying to log on console output what keys are pressed. I just can't understand the cocoa structure, neither with Obj-c, nor swift. I'm not a master in these 2 languages but... Well here's my code:

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)
}

i know everything is wrong, yeah.. But man, these events, i can't understand how they work.

解决方案

After spending a couple of hours on google I eventually read a couple of github resources. It turns out that someone has already figured it out.

Basically you need to create a NSApplicationDelegate, which enables your app to listen to system-events.

The following shows the bare minimum code 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()

If you are just interested in only catching non-accessibility events (e.g.: NSWorkspaceDidActivateApplicationNotification) you can get away with much fewer lines of code as you only need NSRunLoop.mainRunLoop().run(). I only added this example since I saw your while true event-loop, which never will let you listen to any system-events, since its blocking the main-thread.

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()

这篇关于在控制台应用程序中使用swift处理可可键事件(按键)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆