Loading...

How to detect Fn key press in Swift?

question macOS swift
Ram Patra Published on November 10, 2021
Swift 5.0+

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.

Ram Patra Published on November 10, 2021
Image placeholder

Keep reading

If this article was helpful, others might be too

question macOS swift March 14, 2021 How to detect Escape key pressed in macOS apps?

Like Delete key, detection of Escape key press is also slightly different than detecting general key presses.

question macOS swift August 14, 2020 How to quit or close an app in macOS using Swift?

You can quit or exit an app with:NSApp.terminate(self)

question macOS swift March 14, 2021 How to ignore mouse events in a view or window in macOS?

You can ignore mouse events in a window/view by adding just a single line of code.