根据 vb.net 中的 MsoLanguageID 设置 CultureInfo

set CultureInfo based on MsoLanguageID in vb.net

在我的 Microsoft Word 加载项中,我注意到 System.Globalization.CultureInfo.CurrentCulture(或 CurrentUICulture)会给我当前的系统语言,这不一定反映 Word 界面语言。我发现可以使用 Application.LanguageSettings.LanguageID 以这种方式检索:

Dim Application As Word.Application = Globals.{MyAddIn}.Application
Dim lang As Office.MsoLanguageID = Application.LanguageSettings.LanguageID(Office.MsoAppLanguageID.msoLanguageIDUI)

(将 {MyAddIn} 更改为实际的加载项命名空间)。

这将给出 MsoLanguageID 枚举 (https://docs.microsoft.com/en-us/office/vba/api/office.msolanguageid)。有没有什么方法可以根据 MsoLanguageID 设置 CurrentUICulture 而无需手动设置 Select Case 有一百个左右的案例(与中的值一样多) MsoLanguageID 枚举?)

是的,可以自动应用 UI 本地化。您可以将本地化的字符串存储在加载项的资源中,并根据所选的 Office UI 语言即时应用它们。

public void AddinStartup()
{    
    if (this.OfficeApp != null)
        SwitchLanguage(GetLanguageID(this.OfficeApp));
}
 
private int GetLanguageID(dynamic app)
{
    Office.LanguageSettings languageSettings = app.LanguageSettings;
    if (languageSettings != null)
        try
        {
            return languageSettings.LanguageID[Office.MsoAppLanguageID.msoLanguageIDUI];
        }
        finally 
        {
            Marshal.ReleaseComObject(languageSettings); 
        }
    return 0;
}
 
private void SwitchLanguage(int officeLanguageID)
{
    Thread.CurrentThread.CurrentCulture =
        new System.Globalization.CultureInfo(officeLanguageID);
    Thread.CurrentThread.CurrentUICulture =
        new System.Globalization.CultureInfo(officeLanguageID);
 
    ComponentResourceManager resources =
        new ComponentResourceManager(typeof(AddinModule));
    resources.ApplyResources(this.MyRibbonTab, "MyRibbonTab");
    resources.ApplyResources(this.MyRibbonGroup, "MyRibbonGroup");
    resources.ApplyResources(this.MyRibbonButton, "MyRibbonButton");
    resources.ApplyResources(this, "$this");
}