Skip to content

Instantly share code, notes, and snippets.

@joncardasis
Created January 5, 2018 17:35
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save joncardasis/78c7dee7e8de306cfd53e3bb714c6b0a to your computer and use it in GitHub Desktop.
Save joncardasis/78c7dee7e8de306cfd53e3bb714c6b0a to your computer and use it in GitHub Desktop.
Showing/Hiding Menu Bar Items If OPTION is held down (Swift macOS AppKit)
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
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment