Check modifierFlags of NSEvent if a certain modifier was pressed but no other

Maybe even better...

if event.modifierFlags.contains(.shift){
    // do it
}

I think this'll do it:

// Mask out everything but the key flags
NSUInteger flags = [theEvent modifierFlags] & NSEventModifierFlagDeviceIndependentFlagsMask;
if( flags == NSCommandKeyMask ){
    // Got it!
}

Hat tip to SpaceDog for pointing out the deprecation of the original mask name, NSDeviceIndependentModifierFlagsMask.


@JoshCaswell answer has been outdated thanks to Apple, because NSDeviceIndependentModifierFlagsMask has been deprecated since 10.12.

His answer updated to the new syntax is

// Mask out everything but the key flags
NSUInteger flags = [theEvent modifierFlags] & NSEventModifierFlagDeviceIndependentFlagsMask;
if( flags == NSCommandKeyMask ){
  // Got it!
}

NSDeviceIndependentModifierFlagsMask has been replaced with NSEventModifierFlagDeviceIndependentFlagsMask because it makes a world of difference...


Swift 5 version

if event.modifierFlags.intersection(.deviceIndependentFlagsMask) == .command {
    // Got it!
}