Sample Header Ad - 728x90

Change keyboard layout automatically when external keyboard connected

9 votes
1 answer
1936 views
I recently purchased an external keyboard (non-apple) that is used at home and also dragged along with me from time to time, and I've noticed a need. My Mac is in English, as well as its physical keyboard. However, my external keyboard is in Norwegian. I am finding it quite cumbersome to have to swap the keyboard layout every time i swap keyboard, which can be quite often. I noticed that the keyboard layout can change according to the app being used, but this doesn't always work. **Is it possible to make the Mac change its keyboard layout either based on the current keyboard being used or every time I either plug on unplug the external keyboard?** **Something I've already tried** I've created an AppleScript that sort of solves this, but ran into some problems with Mojave and its security, and therefore wondering if I should approach this differently. I'll attach the script for reference, we might have to just alter it if there isn't a better solution.. Would appreciate any thoughts at all. Problem I'm running into is that the app is not allowed to send keystrokes via system events, even though I've permitted it in System Preferences. --Checks connected usb devices for description, performs keypresses if condition is met set devicePresent to false set changeLayout to false delay 2 --delay may not be needed. To make sure that usb device is registred before script is triggered set currentLayout to do shell script "defaults read ~/Library/Preferences/com.apple.HIToolbox.plist AppleSelectedInputSources | egrep -w 'KeyboardLayout Name' | cut -d '=' -f2;exit " set USB to paragraphs of (do shell script "system_profiler SPUSBDataType -detailLevel basic") repeat with i from 1 to (count of USB) if item i of USB contains "Product ID: 0x0059" then set devicePresent to true end repeat if (devicePresent) then if currentLayout contains "ABC" then set changeLayout to true --changes layout to norwegian end if if (not devicePresent) then if currentLayout contains "Norwegian" then set changeLayout to true --changes layout to english end if if (changeLayout) then tell application "System Events" key code 49 using control down set newLayout to do shell script "defaults read ~/Library/Preferences/com.apple.HIToolbox.plist AppleSelectedInputSources | egrep -w 'KeyboardLayout Name' | cut -d '=' -f2;exit " display notification ("Changed layout from " & currentLayout & " to " & newLayout) with title "New Layout" sound name "Sound Name" end tell
Asked by hpl002 (191 rep)
Jan 5, 2019, 10:39 PM
Last activity: Apr 10, 2025, 04:07 AM