jwuki
jwuki

Reputation: 407

OS X key event in menu bar app (Swift)

I've been working on a Cocoa project recently. It's a menu bar/status bar-only application. I need some extra information to appear in the menu bar app when the user holds down the option key, and I've been looking everywhere to see how this is possible without any windows showing onscreen. Is it possible to run keyDown: from AppDelegate.swift to do this? Guidance is appreciated. Thanks!

Upvotes: 1

Views: 1745

Answers (2)

BB9z
BB9z

Reputation: 2720

Do you mean change menu item when user hold the option key?

Checkout isAlternate and keyEquivalentModifierMask properties of menu item.

Also Option (⌥) + Context Menu in Cocoa?

Upvotes: 0

Leo Dabus
Leo Dabus

Reputation: 236538

I am not sure if you can monitor the key down globally but the option key you can do as follow:

NSEvent.addGlobalMonitorForEventsMatchingMask(NSEventMask.FlagsChangedMask) { (theEvent) -> Void in
    if theEvent.modifierFlags.intersect(.DeviceIndependentModifierFlagsMask) == .AlternateKeyMask {
        print("ONLY OPTION")
    }
    switch theEvent.modifierFlags.intersect(.DeviceIndependentModifierFlagsMask) {
    case NSEventModifierFlags.ShiftKeyMask :
        print("shift key is pressed")
    case NSEventModifierFlags.ControlKeyMask:
        print("control key is pressed")
    case NSEventModifierFlags.AlternateKeyMask :
        print("option key is pressed")
    case NSEventModifierFlags.CommandKeyMask:
        print("Command key is pressed")
    default:
        print("no key or more than one is pressed")
    }
}

Upvotes: 1

Related Questions