How to differentiate between user-generated NSEvents and programmatically posted events in AppKit?

Hi all,

In my AppKit app, I sometimes simulate events programmatically, for example:

func simulateKeyPress(characters: String, keyCode: UInt16) {
    guard let keyDown = NSEvent.keyEvent(
        with: .keyDown,
        location: .zero,
        modifierFlags: [],
        timestamp: 0,
        windowNumber: NSApp.mainWindow?.windowNumber ?? 0,
        context: nil,
        characters: characters,
        charactersIgnoringModifiers: characters,
        isARepeat: false,
        keyCode: keyCode
    ) else { return }

    NSApp.postEvent(keyDown, atStart: false)
}

At the same time, I install a local event monitor:

NSEvent.addLocalMonitorForEvents(matching: .any) { event in
    // Ideally, detect whether this event came from a real user
    // (mouse, keyboard, trackpad, etc.)
    // or was programmatically generated via NSEvent + postEvent.
    return event
}

The problem: Events I generate with NSEvent.* factory methods and post using NSApp.postEvent look the same as real system events when received in the monitor.

My question: Is there a supported way to tell whether an incoming NSEvent is system/user-generated vs programmatically posted?

Hi and thanks for asking. Reviewing the API documentation for NSEvent there's no support for that.

If you'd like us to consider adding the necessary functionality, please file an enhancement request using the Feedback Assistant. If you file the request, please post the Feedback number here so we can make sure it gets routed to the right team.

If you're not familiar with how to file enhancement requests, take a look at Bug Reporting: How and Why?

How to differentiate between user-generated NSEvents and programmatically posted events in AppKit?
 
 
Q