Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect fn key press in Swift?

Tags:

macos

swift

I want to detect when the user presses the fn key and do some tasks. I tried the below but it doesn't work:

if event.keyCode == kVK_Function {
   print("fn key pressed")
}

I have similar code for other keys like left bracket, right bracket, slash, alphabets, and numbers. For these keys, the code, shown above, works fine but it doesn't work for fn key. I think this is handled differently.

like image 933
Ram Patra Avatar asked Aug 31 '25 18:08

Ram Patra


1 Answers

You need to check the NSEvent's modifierFlags:

if event.modifierFlags.contains(.function) {
   print("fn key pressed")
}
like image 179
Alexander Avatar answered Sep 02 '25 14:09

Alexander