Using CGEventTapCreate Trouble with parameters in Swift

不问归期 提交于 2019-12-10 11:29:41

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!