views:

156

answers:

1

How can I programmatically change the keyboard layout in Cocoa?

Assume I have, say, two active ones "Estonian" and "U.S." in the System Preferences (i.e. those two layouts visible in the keyboard layout menu bar).

So how would I read that those two are available, and how would I programmatically change between them?

+1  A: 

Use Text Input Source Services if you're on 10.5 or higher. It's based on CoreFoundation, so don't worry it's inside Carbon framework. If you need to support 10.4 or older, you need to use Keyboard Layout Services. I only know the former, so let me explain just that.

You use

CFArrayRef sourceList= TISCreateInputSourceList (NULL,false);

to get the array of TISInputSourceRef corresponding to all the enabled keyboard types. Then you can use other functions to examine them. To select/deselect one, you can use TISSelectInputSource and TISDeselectInputSource, etc.

Don't forget to CFRelease the array you got, though, even in the garbage collected environment, because the garbage-collection of CF objects are not automatic!

Yuji
Yikes, Core Foundation :S Looks like I'm going to have to do some reading on that, as I'm only into Objective-C and Cocoa, not the lower-level stuff. But thanks, I'll try messing with it, see how it goes, and then get back to you.
Enchilada
Don't worry, Core Foundation is just a C API for the OS X object system. It behaves very much like `NSObject`, `NSArray`, etc. In fact `CFArrayRef` can be cast into `NSArray*` and used as such. Apple's documentation is generically very good. Have fun and good luck!
Yuji
It's working really well. Thanks!
Enchilada