I copied and pasted the code from the link below main.swift in command line tool project.
How do you use CGEventTapCreate in Swift?
It builds without an error, but when I run, guard let eventTap = CGEventTapCreate... fails. I think eventTap gets nill from CGEventTapCreate.
I assume because the app is not allowed in the system preference > security and privacy > accessibility. I don't get that notification to allow the app in the accessibility category though. Do I need to set something in project setting to trigger that?
It runs from command line though. I can't run from xCode for some reason.
Here's a slightly modified code from the link above.
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)
print(keyCode)
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()