问题
I am trying to trap keypresses using a CGEventTapCreate etc in Swift. I want to do this so that when my toddler is using a program the Mac, I can limit which keys do something. I appreciate that I need to enable assistive technology to get CGEventTap to work
I am having trouble understanding what I need to do in Swift to get the final parameter in the call. Essentially, I do not understand part of the documentation at quartz event documentation
Specifically the final parameter which is described by
refcon: A pointer to user-defined data. This pointer is passed into the callback function specified in the callback parameter.
Here is my code missing the final parameter from the call
@IBAction func interceptKeyboard(sender: NSButton) {
CGEventTapCreate(kCGSessionEventTap, kCGHeadInsertEventTap, kCGEventTapOptionDefault, CGEventMask((kCGEventKeyDown) | (kCGEventKeyUp)), MyCallBack: kCGHIDEventTap, )
}
func MyCallBack(myLocation:CGEventTapLocation) -> Void{
//do Nowt
}
回答1:
Bit of a while ago, but I think when you look at the type of CGEventTapCallback, you see that it is a CFunctionPointer:
typealias CGEventTapCallBack = CFunctionPointer<((CGEventTapProxy,
CGEventType, CGEvent!, UnsafeMutablePointer<Void>) -> Unmanaged<CGEvent>!)>
At the moment you can't create these in Swift, so you have to dip into objective-c, create a function there, which can then call an equivalent function in Swift, see here:
Objective-C Wrapper for CFunctionPointer to a Swift Closure
I ended up writing the whole of this stuff in Objective-C...
来源:https://stackoverflow.com/questions/26673329/using-cgeventtapcreate-trouble-with-parameters-in-swift