3

Is it possible to observe simulated(not physical) keyboard/mouse events at macOS application ?

I wrote different code to simulate keyboard button presses.

1 Example: Swift

let keyDownEvent = CGEvent(keyboardEventSource: CGEventSource(stateID: CGEventSourceStateID.hidSystemState), virtualKey: virtualKey, keyDown: true)

keyDownEvent?.post(tap: CGEventTapLocation.cghidEventTap)

2 Example: Obj-c / C++

-(void)HIDPostAuxKey:(const UInt8)auxKeyCode  {
__block NXEventData   event;
__block kern_return_t kr;
__block IOGPoint      loc = { 0, 0 };

// Key press event
__block UInt32 evtInfo = auxKeyCode << 16 | NX_KEYDOWN << 8;
bzero(&event, sizeof(NXEventData));
event.key.origCharSet = event.key.charSet = NX_ASCIISET;
event.compound.subType = NX_SUBTYPE_AUX_CONTROL_BUTTONS;
event.compound.misc.L[0] = evtInfo;
//    event.key.repeat = true;
kr = IOHIDPostEvent( get_event_driver(), NX_SYSDEFINED, loc, &event, kNXEventDataVersion, 0, FALSE );
assert( KERN_SUCCESS == kr );

// Key release event
dispatch_time_t delay = dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC * 100);
dispatch_after(delay, dispatch_get_main_queue(), ^(void){
    evtInfo = auxKeyCode << 16 | NX_KEYUP << 8;
    bzero(&event, sizeof(NXEventData));
    event.key.origCharSet = event.key.charSet = NX_ASCIISET;
    event.compound.subType = NX_SUBTYPE_AUX_CONTROL_BUTTONS;
    event.compound.misc.L[0] = evtInfo;
    kr = IOHIDPostEvent( get_event_driver(), NX_SYSDEFINED, loc, &event, kNXEventDataVersion, 0, FALSE );
    assert( KERN_SUCCESS == kr );
}); }

Since Apple removed access to handle keyboard presses, without enabled accessibility in Settings if macOS app is in background, such api as this:

NSEvent.addGlobalMonitorForEvents(matching: [.keyDown, .keyUp]) { (event) in
        debugPrint("any key button tapped")
}

now does not work.

The only workable solution, that I found, was IOKit, low-level api https://stackoverflow.com/a/39834889/7141905, that listens to keyboard/mouse events even without enabled accessibility for app.

But none of these two ways can observe/catch simulating keyboard presses. It can observe only physical events from user's input. Carbon Framework is not suitable for my case too.

More info about accessibility requirements here: https://github.com/KonsomeJona/OctoMouse#why-is-the-keystrokes-counter-not-working

0 Answers0