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.

3
  • Is the current runloop the main runloop? In Objective-C I have to convert each event type to a mask using CGEventMaskBit. Commented Jan 30, 2017 at 17:30
  • Yes is the main runloop. If I use CGEventMaskBit, the eventTap is null. Commented Jan 30, 2017 at 18:57
  • The main runloop is already running. How do you use CGEventMaskBit? Commented Feb 2, 2017 at 16:31

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.