大佬教程收集整理的这篇文章主要介绍了你如何在Swift中使用CGEventTapCreate?,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
这是去年的参考SO帖子:Using CGEventTapCreate Trouble with parameters in Swift
以下是CGEventTapCallBACk的定义方式:
typealias CGEventTapCallBACk = CFunctionPointer<((CGEventTapProxy,CGEventType,CGEvent!,UnsafeMutablePointer<Void>) -> Unmanaged<CGEvent>!)>
以下是我编写块的方法:
let eventTapCallBACkBlock : @objc_block (CGEventTapProxy,CGEventRef,UnsafeMutablePointer<Void>) -> CGEventRef = { (eventTapProxy: CGEventTapProxy,eventType: CGEventType,event: CGEventRef,refcon: UnsafeMutablePointer<Void>) in return event }
然后我用回调参数调用CGEventTapCreate,如unsafeBitCast(eventTapCallBACkBlock,CGEventTapCallBACk.self)
我得到一个有效的CFMachPortRef,但在运行时我在第一个事件上遇到访问冲突异常.它似乎“似乎”我在当前发布状态下接近迅速解决方案.
使用Xcode版本6.4
但是,在Swift 2(Xcode 7)中,C函数接受函数指针参数
可以使用闭包或全局函数调用(具有限制
闭包不得捕获任何本地语境).
作为一个例子,这里是一个完整的翻译
Receiving,Filtering,and Modifying Key Presses and Releases
到斯威夫特:
import Foundation func myCGEventCallBACk(proxy : CGEventTapProxy,type : CGEventType,event : CGEvent,refcon : UnsafeMutablePointer<Void>) -> Unmanaged<CGEvent>? { if [.KeyDown,.KeyUp].contains(typE) { var keyCode = CGEventGetIntegerValueField(event,.KeyboardEventKeycodE) if keyCode == 0 { keyCode = 6 } else if keyCode == 6 { keyCode = 0 } CGEventSetIntegerValueField(event,.KeyboardEventKeycode,keyCodE) } return Unmanaged.passRetained(event) } let eventMask = (1 << CGEventType.KeyDown.rawvalue) | (1 << CGEventType.KeyUp.rawvalue) guard let eventTap = CGEventTapCreate(.CGSessionEventTap,.HeadInsertEventTap,.Default,CGEventMask(eventMask),myCGEventCallBACk,nil) else { print("Failed to create event tap") exit(1) } let runLoopsource = CFMachPortCreateRunLoopsource(kcfAllocatorDefault,eventTap,0) CFRunLoopAddsource(CFRunLoopGetCurrent(),runLoopsource,kcfRunLoopCommonModes) CGEventTapEnable(eventTap,truE) CFRunLoopRun()
Swift 3更新:
import Foundation func myCGEventCallBACk(proxy: CGEventTapProxy,type: CGEventType,event: CGEvent,refcon: UnsafeMutableRawPointer?) -> Unmanaged<CGEvent>? { if [.keyDown,.keyUp].contains(typE) { var keyCode = event.getIntegerValueField(.keyboardEventKeycodE) if keyCode == 0 { keyCode = 6 } else if keyCode == 6 { keyCode = 0 } event.setIntegerValueField(.keyboardEventKeycode,value: keyCodE) } return Unmanaged.passRetained(event) } let eventMask = (1 << CGEventType.keyDown.rawvalue) | (1 << CGEventType.keyUp.rawvalue) guard let eventTap = CGEvent.tapCreate(tap: .cgSessionEventTap,place: .headInsertEventTap,options: .defaultTap,eventsOfInterest: CGEventMask(eventMask),callBACk: myCGEventCallBACk,userInfo: nil) else { print("Failed to create event tap") exit(1) } let runLoopsource = CFMachPortCreateRunLoopsource(kcfAllocatorDefault,.commonModes) CGEvent.tapEnable(tap: eventTap,enable: truE) CFRunLoopRun()
以上是大佬教程为你收集整理的你如何在Swift中使用CGEventTapCreate?全部内容,希望文章能够帮你解决你如何在Swift中使用CGEventTapCreate?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。