macOS: Is it possible to detect when the “fn” key

2019-08-15 03:41发布

问题:

I'm curious if it's possible to detect when the "fn" key is pressed on a mac keyboard, either when it's used on its own or when used in combination with another key. Is there a way to do that? I'm open to using any sort of method, including undocumented Apple APIs if necessary.

回答1:

All keyboard NSEvents will have NSEventModifierFlagFunction (NSEvent.ModifierFlags.function in Swift) in their .modifierFlags when the Fn key is down.

To test for Fn on its own rather than in combination with some other keyboard event, it appears that when the Fn key is depressed or released, an NSEvent gets sent with type NSFlagsChanged (NSEvent.EventType.flagsChanged in Swift).