F2 key press event for macOS

Why kVK_F2 is not equivalent to constant NSF2FunctionKey for F2 key press event, What is equivalent constant of kVK_F2, since carbon framework is deprecated.

When I printed the keyCode, The [Event keyCode] against NSF2FunctionKey is 63237(0xF705) whereas for kVK_F2, it prints is 120 which is 0x78. 0x78 seems to be the standard keyboard value for F2 key.

Sample code :

//@property (nonatomic, strong) id eventMonitor;  

NSEvent* (^handler)(NSEvent*) = ^(NSEvent *theEvent) {

        NSEvent *result = theEvent;
        NSUInteger flags = [theEvent modifierFlags] & NSEventModifierFlagDeviceIndependentFlagsMask;

        if ((flags & NSEventModifierFlagFunction) && (flags & NSEventModifierFlagCommand) && ([theEvent keyCode] == NSF2FunctionKey)) {
            NSLog(@"Command + F2 key pressed.");
        }

        return result;
    };

_eventMonitor = [NSEvent addLocalMonitorForEventsMatchingMask:(NSEventModifierFlagFunction | NSEventMaskKeyDown) handler:handler];

Replies

I wouldn’t worry about using the Carbon declarations for this [1].

Having said that, it’s fine to hard code these values. These virtual keycodes were literally burnt into the firmware of millions of ADB keyboards. They’re not going to change.

Having said that, if you’re uncomfortable with this situation, you should absolutely file a bug the macOS SDK to get new declarations in a more sustainable place.

If you do file a bug, please post your bug number, just for the record.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

[1] The deprecation story for Carbon is a complex one, as I was explaining to someone just yesterday.