måndag 22 april 2013

Automatically change keyboard settings

When using an external (Windows) keyboard with your Mac you probably want to modify your keyboard layout, for instance change Windows button to Option and Alt button to Command.

A nice program for this is KeyRemap4MacBook, but that is not what this article is about, since there is a lot of information about that program already on the web.

My issue is that I switch a lot between the laptop keyboard and the external keyboard, depending on if I sit by my desk or not. There is a nice thing i KeyRemap4MacBook to switch profiles. However I do not want to manually switch profiles every time I (dis-)connect my external keyboard.

So I created a bash script that detects if an external keyboard is connected and then I schedule this with crontab.

The script:

#!/bin/bash
externalConnected=`/usr/sbin/system_profiler SPUSBDataType|grep -i keyboard|grep -vi internal`
if [[ "" == "$externalConnected" ]]; then
newSetting=1
else
newSetting=0
fi
currentSetting=`/usr/libexec/PlistBuddy -c "Print :selectedIndex" ~/Library/Preferences/org.pqrs.KeyRemap4MacBook.plist`
if [[ $newSetting != $currentSetting ]]; then
/usr/libexec/PlistBuddy -c "Set :selectedIndex $newSetting" ~/Library/Preferences/org.pqrs.KeyRemap4MacBook.plist
killall KeyRemap4MacBook
fi

This assumes that you have two profiles in KeyRemap4MacBook and that the first one is the profile for the external keyboard!

Crontab:
* * * * * ~/Scripts/detect_external_keyboard.sh
* * * * * sleep 15; ~/Scripts/detect_external_keyboard.sh
* * * * * sleep 30; ~/Scripts/detect_external_keyboard.sh
* * * * * sleep 45; ~/Scripts/detect_external_keyboard.sh

As you see I had to add 4 rows to make it run more often than once per minute.

Inga kommentarer:

Skicka en kommentar