Solution using Xcode Command Line Tools
For those, who would like to build @Ken Thomases' solution but without installing Xcode (which is several GiB and is totally useless to spend so much space on unless used seriously) it is possible to build it using the Xcode Command Line Tools.
There are several tutorials on the internet about how to install Xcode Command Line Tools. The point here is only that it takes fraction of the space compared to full-blown Xcode.
Once you have it installed, these are the steps:
- Create a file called whatever.m
- In whatever.m put the following:
#include <Carbon/Carbon.h>
int main (int argc, const char * argv[]) {
NSArray* sources = CFBridgingRelease(TISCreateInputSourceList((__bridge CFDictionaryRef)@{ (__bridge NSString*)kTISPropertyInputSourceID : @"com.apple.keylayout.French" }, FALSE));
TISInputSourceRef source = (__bridge TISInputSourceRef)sources[0];
OSStatus status = TISSelectInputSource(source);
if (status != noErr)
return -1;
return 0;
}
- Replace
French
with your desired layout.
- Save the file
- Open terminal in the same folder as whatever.m is
- Run this command:
clang -framework Carbon whatever.m -o whatever
Your application is created as whatever
in the same folder and can be executed as:
.\whatever
Additionally
I've never created any Objective-C programs, so this may be suboptimal, but I wanted an executable that can take the keyboard layout as a command line parameter. For anyone interested, here's the solution I came up with:
In step 2 use this code:
#import <Foundation/Foundation.h>
#include <Carbon/Carbon.h>
int main (int argc, const char * argv[]) {
NSArray *arguments = [[NSProcessInfo processInfo] arguments];
NSArray* sources = CFBridgingRelease(TISCreateInputSourceList((__bridge CFDictionaryRef)@{ (__bridge NSString*)kTISPropertyInputSourceID : [@"com.apple.keylayout." stringByAppendingString:arguments[1]] }, FALSE));
TISInputSourceRef source = (__bridge TISInputSourceRef)sources[0];
OSStatus status = TISSelectInputSource(source);
if (status != noErr)
return -1;
return 0;
}
In step 6. run this command:
clang -framework Carbon -framework Foundation whatever.m -o whatever
You can now switch to any layout from the command line, e.g.:
./whatever British
Note: it only allows to switch to layouts already configured on your system!