How to consume CAPS-LOCK event on MacOS

戏子无情 提交于 2019-12-11 17:22:50

问题


I am trying to remap CAPS-LOCK.

I can successfully detect CAPS-LOCK key-down/up events using CGEventTap.

However, I am unable to consume them. (OTOH I am able to consume ordinary key-down/up events).

The below code excerpt illustrates this:

@implementation Intercept

- (BOOL) tapEvents
{
    _eventTap = CGEventTapCreate( kCGHIDEventTap, // kCGSessionEventTap,
                                  kCGHeadInsertEventTap,
                                  kCGEventTapOptionDefault,
                                       CGEventMaskBit( NSEventTypeKeyDown )
                                     | CGEventMaskBit( NSEventTypeFlagsChanged )
                                     | CGEventMaskBit( NSEventTypeSystemDefined ),
                                  (CGEventTapCallBack) tapCallback,
                                  (__bridge void *)(self));
    CGEventTapEnable( _eventTap, YES );
}


CGEventRef tapCallback(
                        CGEventTapProxy proxy,
                        CGEventType     type,
                        CGEventRef      event,
                        Intercept*     listener
                        )
{
    return [listener interceptEvent:event];
}


- (CGEventRef)interceptEvent:(CGEventRef)cgEvent
{    
    NSEvent* event = [NSEvent eventWithCGEvent:cgEvent];

    /*
     CAPSLOCK sends:
       (1) NSEventTypeSystemDefined
       (2) NSEventTypeFlagsChanged
     */

    switch( event.type ) {
        // if I return NULL here, it DOESN'T eat CAPS-LOCK
        case NSEventTypeFlagsChanged:
        case NSEventTypeSystemDefined:
            return NULL;

        // if I return NULL here, it DOES eat keystrokes
        case NSEventTypeKeyDown:
            return NULL;
    }

    CGEventRef ev = [event CGEvent];
    CFRetain(ev);
    return ev;
}

How come this one key escapes the rules that bind the rest?

Do I have to drop down to IOHID layer?

REF: Simulate/Toggle CAPS LOCK programatically in OS X

Alternatively, might it make sense to inject antidote CAPS-LOCK events that will cancel the effect of the real ones?

来源:https://stackoverflow.com/questions/56311610/how-to-consume-caps-lock-event-on-macos

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!