OS X key event in menu bar app (Swift)

匿名 (未验证) 提交于 2019-12-03 10:24:21

问题:

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!

回答1:

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")     } } 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!