2009-04-23 122 views
4

如何学习当前选定的键盘布局/输入语言?Cocoa:学习当前选定的键盘布局/输入语言

我在玩NSInputManager,但无法实现任何功能。

[NSInputManager currentInputManager] 

返回(NULL)(作为报道%@),因此

[[NSInputManager currentInputManager] localizedInputManagerName] 

这将是最适合我刚刚回来使用像EN或语言的两个字母的缩写FR,但菜单栏中显示的键盘布局名称也可以使用。

任何想法?谢谢。

编辑:我还发现一个AppleSelectedInputSourcesChangedNotification被贴到

[NSDistributedNotificationCenter defaultCenter] 

当用户改变了布局,但没有关于新选择的布局信息被“附加”此通知。

回答

12

对语言组合的键盘布局通常是一对多的,所以虽然您可以获取当前所选键盘布局(或更一般地说,输入源)的本地化名称,但可使用该源键入文本在许多语言中。你为什么想这样做?

也就是说,您可以使用Text Input Source Services获取有关当前文本输入源的信息。例如:

TISInputSourceRef source = TISCopyCurrentKeyboardInputSource(); 
    NSLog(@"languages: %@", 
     TISGetInputSourceProperty(source, kTISPropertyInputSourceLanguages)); 
    NSLog(@"localized name: %@", 
     TISGetInputSourceProperty(source, kTISPropertyLocalizedName)); 

给我:

2009-04-23 14:30:17.581 sample[30688:10b] languages: (
    en, 
    ca, 
    da, 
    de, 
    es, 
    eu, 
    fr, 
    ga, 
    gl, 
    gv, 
    id, 
    it, 
    kw, 
    ms, 
    nb, 
    nl, 
    nn, 
    om, 
    pt, 
    so, 
    sq, 
    sv, 
    sw 
) 
2009-04-23 14:30:17.584 sample[30688:10b] localized name: U.S. 
+0

我想也与这些玩,但WASN”甚至可以编译它。你添加了什么框架和什么#imports? :-)另外,你认为这只适用于碳吗? – 2009-04-24 04:14:45

+1

`#import `(或`#include`也可以使用,因为Carbon头文件包含守卫)。然后,您需要在Xcode中将Carbon框架添加到您的项目中(或者,如果您正在编译,请使用`-framework Carbon`)。请注意,尽管这在技术上是“碳”和“HIToolbox”,但它与Carbon和Cocoa交谈的低级碳都支持64位应用程序,并且不会很快消失,所以不要觉得你不能使用它。 – 2009-04-24 04:44:32

1

这里的可可只(现代)这样的方式:

+ (NSString *) userLanguagePreference { 
    NSArray *languages = [[NSUserDefaults standardUserDefaults] objectForKey:@"AppleLanguages"]; 
    NSString *primaryLanguage = [languages objectAtIndex:0]; 
    return [self localeCodeToString: primaryLanguage]; 
} 

+ (NSString *) userInputSourcePreference { 
    NSString *userInputSource = [[NSLocale currentLocale] localeIdentifier]; 
    return [[NSLocale currentLocale] displayNameForKey:NSLocaleIdentifier value:userInputSource]; 
}