问题
I was trying to find a solution to this because I am using Vim and most of the time I need Caps lock to be assigned to Ctrl. There are times though that I want the Caps Lock working normally. I thought an Apple Script is great as it can be assigned to a LaunchBar action.
I will answer with the solution I ended up with (through GUI scripting) but would be interested in a less intrusive solution if someone knows a way...
回答1:
You can use PCKeyboardHack to change caps lock to F19. Then save this as private.xml:
<?xml version="1.0"?>
<root>
<item>
<name>caps1</name>
<identifier>caps1</identifier>
<autogen>__KeyToKey__ KeyCode::F19, KeyCode::CAPSLOCK</autogen>
</item>
<item>
<name>caps2</name>
<identifier>caps2</identifier>
<autogen>__KeyToKey__ KeyCode::F19, KeyCode::CONTROL_L</autogen>
</item>
</root>
And use this script to toggle the settings:
k=/Applications/KeyRemap4MacBook.app/Contents/Applications/KeyRemap4MacBook_cli.app/Contents/MacOS/KeyRemap4MacBook_cli
if $k changed | grep -q ^caps1=; then
$k disable caps1
$k enable caps2
else
$k enable caps1
$k disable caps2
fi
It would be easier to just assign another key combination to caps lock though:
<autogen>__KeyOverlaidModifier__ KeyCode::CONTROL_L, ModifierFlag::FN, KeyCode::CONTROL_L, ModifierFlag::FN, KeyCode::CAPSLOCK</autogen>
This would be triggered on key down, so you'd have to press control before fn for key combinations like fn+control+down:
<autogen>__KeyToKey__ KeyCode::CONTROL_L, ModifierFlag::FN, KeyCode::CAPSLOCK</autogen>
回答2:
This is the script I am currently using:
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
click button "Modifier Keys…" of tab group 1 of window "Keyboard"
tell sheet 1 of window "Keyboard"
click pop up button 4
set capsLockCurrentlyOn to (value of attribute "AXMenuItemMarkChar" of menu item 1 of menu 1 of pop up button 4 as string) ≠ ""
--display dialog "Caps Lock On: " & capsLockCurrentlyOn
if capsLockCurrentlyOn is true then
--tell me to beep 3
click menu item 2 of menu 1 of pop up button 4
else
--tell me to beep 2
click menu item 1 of menu 1 of pop up button 4
end if
click button "OK"
end tell
end tell
tell application "System Preferences" to quit
end tell
回答3:
Did you try KeyRemap4MacBook or PCKeyboardHack?
来源:https://stackoverflow.com/questions/16093042/applescript-script-to-switch-caps-lock-key-to-control