random($foo)

Reverse Keyboard Mapping AppleScript

I've been switching between my Macbook Pro's internal keyboard and an external Microsoft Natural keyboard fairly regularly, so the reversed option/command key problem has been a pretty constant thorn in my side. I couldn't get the 10.4: Change keymapping only on external keyboards hint to work (I probably just need to clear some of those kernel caches after changing the mapping), so I finally got pissed off enough to write an AppleScript to help. That way, I only need to worry about the switched keys for one Quicksilver call. :)

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

tell application "System Events"
	get properties
	tell application process "System Preferences"
		click button "Modifier Keys…" of tab group 1 of window "Keyboard & Mouse"
		
		set commandKey to value of pop up button 3 of sheet 1 of window "Keyboard & Mouse"
		
		-- DEBUG
		-- display dialog commandKey
		
		--  Default, lets flip
		if commandKey ends with "Option" then
			-- click the pop up button menu "Option", this menu does not exist until it is clicked in the GUI
			click pop up button 3 of sheet 1 of window "Keyboard & Mouse"
			-- click "Command" of the pop up menu
			click menu item 4 of menu 1 of pop up button 3 of sheet 1 of window "Keyboard & Mouse"
			
			-- delay briefly
			delay 1
			
			-- click the pop up button menu "Command", this menu does not exist until it is clicked in the GUI
			click pop up button 4 of sheet 1 of window "Keyboard & Mouse"
			-- click "Option" of the pop up menu
			click menu item 3 of menu 1 of pop up button 4 of sheet 1 of window "Keyboard & Mouse"
			
			-- Not Default, lets flip it back
		else
			click button "Restore Defaults" of sheet 1 of window "Keyboard & Mouse"
		end if
		
		-- click "OK" to dismiss the sheet
		click button "OK" of sheet 1 of window "Keyboard & Mouse"
		
	end tell
end tell

tell application "System Preferences" to quit

As always, looking up what objects/properties to call is suitably obscure, but I think I'm getting better at this.

2006-06-21 15:54:32