Daniel
Daniel

Reputation: 161

How to get keyboard layout in Mac OS X with C/C++

I need to get the keyboard layout being used on Mac OS X. I've found old restonces to this but they all are something like this:

How to change the Mac OS X Keyboard Layout programmatically?

which doesn't work any more. Any help would be much appreciated.

Upvotes: 1

Views: 1398

Answers (2)

Daniel
Daniel

Reputation: 161

In case someone is interested, I was finally able to get the keyboard layout with the following code:

#include <Carbon/Carbon.h>
int main() {
    char layout[128];
    memset(layout, '\0', sizeof(layout));
    TISInputSourceRef source = TISCopyCurrentKeyboardInputSource();
    // get input source id - kTISPropertyInputSourceID
    // get layout name - kTISPropertyLocalizedName
    CFStringRef layoutID = TISGetInputSourceProperty(source, kTISPropertyInputSourceID);
    CFStringGetCString(layoutID, layout, sizeof(layout), kCFStringEncodingUTF8);
    printf("%s\n", layout);
    return 0;
}

Compiled with:

gcc -o test2 test2.c -framework Carbon

Upvotes: 4

Therese Farah
Therese Farah

Reputation: 35

I would try this:

#import <Carbon/Carbon.h>

TISInputSourceRef source = TISCopyCurrentKeyboardInputSource();
NSString *s = (__bridge NSString *)(TISGetInputSourceProperty(source, kTISPropertyInputSourceID));

Upvotes: 0

Related Questions