2

I want to make an app that will force the user to take a break for a specific time. I can't find a way to do that. Until now, i was about to use CGEvent to recive a notification when a key is pressed, but work only for mouse input.

 let eventMask = 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, eventTap, 0)
    CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, .commonModes)
    CGEvent.tapEnable(tap: eventTap, enable: true)
    CFRunLoopRun()

Does not matter what event mask is set, callback is trigger only from mouse action.

So my question is split in two:

  1. Why above code does not trigger on keydown
  2. Is any other way to achieve that task?

Thanks.

C-Viorel
  • 1,801
  • 3
  • 22
  • 41

1 Answers1

1

You can do this using CGEventTap but it requires that the application is given accessibility permissions in "System Preferences - Security & Privacy - Privacy - Accessibility".

See this answer for a complete example.

If you need help converting this to Swift, let me know.

Community
  • 1
  • 1
lemonmojo
  • 733
  • 5
  • 20