问题描述
我是Swift和Xcode的新手,下一个问题是
I am new to Swift and Xcode and I have next problem:
我有一个带有一个计数器(Label
)的简单Cocoa Swift应用程序.
I have simple Cocoa Swift Application with one counter (Label
).
如何处理Mac(在所有应用程序中)中的所有鼠标单击并将其显示在我的Label
中?
How to handle all mouse clicks in my Mac (in all applications) and display it in my Label
?
我使用Xcode 7.3.1.
I use Xcode 7.3.1.
更新1.我已经发现它是监视可可中的事件和addGlobalMonitorForEventsMatchingMask:handler:
功能,但是我不确定自己的方法是否正确.
UPDATE 1. What I have already found it's Monitoring Events and addGlobalMonitorForEventsMatchingMask:handler:
function in Cocoa, but I'm not sure that I'm on the right way.
推荐答案
关于使用 addGlobalMonitorForEventsMatchingMask:handler:
一个简单的示例可能看起来像这样:
A simple example might look something like this:
AppDelegate.swift
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet weak var window: NSWindow!
@IBOutlet var textLabel : NSTextField!
var eventHandler : GlobalEventMonitor?
var gecount : Int = 0
func applicationDidFinishLaunching(aNotification: NSNotification) {
eventHandler = GlobalEventMonitor(mask: .LeftMouseDownMask, handler: { (mouseEvent: NSEvent?) in
self.gecount += 1
self.textLabel.stringValue = "global event monitor: \(self.gecount)"
})
eventHandler?.start()
}
}
GlobalEventMonitor.swift
public class GlobalEventMonitor {
private var monitor: AnyObject?
private let mask: NSEventMask
private let handler: NSEvent? -> ()
public init(mask: NSEventMask, handler: NSEvent? -> ()) {
self.mask = mask
self.handler = handler
}
deinit {
stop()
}
public func start() {
monitor = NSEvent.addGlobalMonitorForEventsMatchingMask(mask, handler: handler)
}
public func stop() {
if monitor != nil {
NSEvent.removeMonitor(monitor!)
monitor = nil
}
}
}
为了捕获应用程序中的事件,您可以使用 addLocalMonitorForEventsMatchingMask:handler:
或 NSClickGestureRecognizer
对象.
In order to capture events within your app your can either use the addLocalMonitorForEventsMatchingMask:handler:
or the NSClickGestureRecognizer
object.
如果要将全局事件监视器与手势识别器对象组合在一起,只需将两个对象都实现到类中即可.
If you wanted to combine the global event monitor with the gesture recognizer object it's simply a matter of implementing both objects into your class.
这篇关于在OS X上使用Swift.如何处理全局鼠标事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!