3

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()
Community
  • 1
  • 1
jl303
  • 1,461
  • 15
  • 27

1 Answers1

0

If you are using Swift3, then the CGEventTap constants should begin with lowercase letters. For example:

.CGSessionEventTap should be .cgSessionEventTap

The same holds true for .keyDown, .keyUp, .headInsertEventTap, etc,...

In order to run from Xcode, you need to add the Xcode.app to: System Preferences > Security & Privacy panel (not the app that you are building).

To run without Xcode, you will need to make your app a trusted accessibility client by calling isProcessTrusted from your applicationDidFinishLaunching method.

RGB World
  • 399
  • 1
  • 6
  • 19