Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Aileonzlc/06e46d149dce2fd3dc9fd068f16a46f7 to your computer and use it in GitHub Desktop.
Save Aileonzlc/06e46d149dce2fd3dc9fd068f16a46f7 to your computer and use it in GitHub Desktop.

Revisions

  1. @joncardasis joncardasis created this gist Jan 5, 2018.
    47 changes: 47 additions & 0 deletions MenuBarOptionKeyListener.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,47 @@
    class AppDeleatate: NSObject, NSApplicationDelegate {
    fileprivate var optionalMenuItems = [NSMenuItem]()
    //...

    func applicationDidFinishLaunching(_ aNotification: Notification) {
    //...
    let specialItem = NSMenuItem(title: MenuBarItemLabelText.specialItem, action: #selector(doNeatAction), keyEquivalent: "")
    specialItem.isHidden = true

    optionalMenuItems.append(specialItem)
    //...
    }
    }

    //MARK: NSMenuDelegate + Option key shows additional menu items
    extension AppDelegate: NSMenuDelegate {

    func menuWillOpen(_ menu: NSMenu) {
    if menuObserver == nil {
    menuObserver = CFRunLoopObserverCreateWithHandler(nil, CFRunLoopActivity.beforeWaiting.rawValue, true, 0, { (observer, activity) in
    self.menuRecievedEvents()
    })

    CFRunLoopAddObserver(CFRunLoopGetCurrent(), menuObserver, CFRunLoopMode.commonModes)
    }
    }

    func menuDidClose(_ menu: NSMenu) {
    guard menuObserver != nil else {
    return
    }
    CFRunLoopObserverInvalidate(menuObserver)
    menuObserver = nil
    }

    /// Will update the active menu. Used to update for events such as `OPTION` key presses.
    fileprivate func menuRecievedEvents() {
    // Get global modifier key flags
    let event = CGEvent(source: nil)
    let flags: CGEventFlags = event!.flags
    let optionKeyIsPressed = CGEventFlags(rawValue: flags.rawValue & CGEventFlags.maskAlternate.rawValue) == CGEventFlags.maskAlternate

    for item in optionalMenuItems {
    item.isHidden = !optionKeyIsPressed
    }
    }
    }