You can override the flagsChanged()
method of NSViewController
and have your code like below to detect fn
key press and release in macOS:
override func flagsChanged(with event: NSEvent) {
if event.modifierFlags.intersection(.deviceIndependentFlagsMask).contains(.function) {
print("fn key pressed")
}
if event.modifierFlags.intersection(.deviceIndependentFlagsMask) == [] {
print("fn key released")
}
}
P.S. The above solution was derived from this answer on SOF. This solution would also work for any of the modifier keys like Cmd, Shift, Opt, etc. However, note that this would be triggered even if a user has the fn key pressed all the time but presses/releases any other modifier keys. The above code doesn’t exactly detect fn key presses but rather whether the fn key is present in the list of modifier keys being pressed/released.