Search code examples
swiftmacoscocoansmenuitemnsstatusitem

NSStatusItem and NSMenuItem detect shift press


I'm trying to modify my NSMenuItems in my NSStatusItem when the shift button is clicked. Basically I want to modify the text from "MenuItem123" to "Shift MenuItem123"

I tried adding

NSEvent.addLocalMonitorForEventsMatchingMask

and

NSEvent.addGlobalMonitorForEventsMatchingMask

which work for my regular window apps, but for NSStatusItem/NSMenuItems the completion blocks aren't called or are called but only when the menu isn't displayed.


Solution

  • You don't need to listen to events in order to show alternate menu items. You only need create two menu items and mark the second one as alternate and also set its keyEquivalentModifierMask to NSShiftKeyMask. Assuming you have a variable called statusItem you can use the following code snippet:

    let menu = NSMenu();
    
    menu.addItemWithTitle("MenuItem123", action:"test:", keyEquivalent:"")
    if let shiftItem = menu.addItemWithTitle("Shift MenuItem123", action:"test:", keyEquivalent:"") {
        shiftItem.alternate = true
        shiftItem.keyEquivalentModifierMask = Int(NSEventModifierFlags.ShiftKeyMask.rawValue)
    }
    
    statusItem.menu = menu