Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
375 views
in Technique[技术] by (71.8m points)

capslock - How to consume CAPS-LOCK event on MacOS

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...