Keyboard shortcut to toggle FN state

applescript automation

Originally posted as GitHub Gist on 25 Jan 2017 , updated at 19 Apr 2021 (details)


Source: https://gist.github.com/paulera/d6a89b769877666f269515501b252c5d

Description: Script to toggle the FN Lock state in MacOS.


fn-toggle.scpt

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# toggle-fn.scpt
# 
# This AppleScript toggles the FN key state.
#
# To assign a keyboard shortcut (long story short):
# Export this AppleScript to an app (a service to just run the script won't have accessibility privileges)
# ----> In the script editor, go to File -> Export, change format to "Application" and save. It will create a .app file.
# When you try to run for the first time, it will ask for access to Accessibility control. Allow it.
# Create a service in Automator to open the app.
# Create a keyboard shortcut to run the service created in Automator.
#
# Follow: @paulo_dev

tell application "System Preferences"
	activate
	set current pane to pane "com.apple.preference.keyboard"
end tell

tell application "System Events"
	tell application process "System Preferences"
		
		get properties
		
		delay 0.3
		# Troubleshooting:
		# Problem: Can’t get window "Keyboard" of application process "System Preferences"
		# Solution: tweak the delay to a higher value
		
		click radio button "Keyboard" of tab group 1 of window "Keyboard"
		
		set theCheckbox to checkbox "Use F1, F2, etc. keys as standard function keys" of tab group 1 of window "Keyboard"
		# Troubleshoot
		# Problem: Can’t get window "Keyboard" of application process "System Preferences"
		# Solution: fix the "click checkbox" using the exact text found in System Preferences -> Keyboard -> Keyboard (tab) for you MacOS version
		
		click theCheckbox
		
		tell theCheckbox
			if (its value as boolean) then
				display notification "Using standard F1, F2, F3, F4, ..."
			else
				display notification "FN Locked (special function keys activated)"
			end if
			delay 1 # necessary to keep the notification, otherwise it will die with the script
		end tell
		
	end tell
	
	tell application "System Preferences" to quit
end tell

# --------------------------------------------------------------------
# Originally seen in http://forums.macrumors.com/threads/how-to-f-lock.313721/