Search code examples
macosinternationalizationtextinput

How to change the user's input method (eg. U.S. vs. Arabic) on OS X?


Writing a vocabulary trainer for Arabic, my program shall automatically switch the input method between the user's default language and arabic.

On Windows, this can be done with LoadKeyboardLayout and ActivateKeyboardLayout.

Is there an API call to accomplish the same on OS X?

It's okay to require the user to enable the Arabic kbd layout once himself via the System prefs, but him having to switch back and forth manually every time is a nuisance I want to avoid.

Or, alternatively, can I assign the preferred input method to a Carbon text input field so that I could use two input fields, one for U.S., one for Arabic, that way?


Solution

  • You need the Carbon api, look at Text Input Source Services Reference

    Here is a sample code without error handling (Mac OS X v10.5 and later)

    CFStringRef tID = CFSTR("com.apple.keylayout.Arabic"); // or "com.apple.keylayout.US"
    TISInputSourceRef inputSource = NULL;
    CFArrayRef allInputs = TISCreateInputSourceList(NULL, true);
    NSUInteger count = CFArrayGetCount(allInputs);
    for (int i = 0; i < count; i++) {
        inputSource = (TISInputSourceRef)CFArrayGetValueAtIndex(allInputs, i);
        if (!CFStringCompare(tID, TISGetInputSourceProperty(inputSource, kTISPropertyInputSourceID), 0)) {
            TISEnableInputSource(inputSource);
            TISSelectInputSource(inputSource);
            break;
        }
    }
    CFRelease(allInputs);