0

我有以下代码在静态模式下转换控件,即通过编写翻译后的字符串(法语、德语等)并保存资源文件并调用它。如果我需要动态翻译(包括用户输入),比如谷歌翻译器的工作方式。我需要在离线模式下实现相同的功能。有没有可能像翻译一样访问谷歌,它会立即/动态翻译成所选语言,但离线?或者请建议我任何首选方法。

foreach (Control c in this.Controls)
    {
        ComponentResourceManager resources = new ComponentResourceManager(typeof(MainForm));
        resources.ApplyResources(c, c.Name, new CultureInfo(lang));
    }

——问候,马诺哈尔。

4

1 回答 1

0

我不知道它是否对你有帮助,但这就是我所做的。它是用托管 c++ /clr 编写的,您可以轻松地将其翻译成 c#。我写了一个小助手类来管理翻译过程

(您可以在运行时更改语言!它会立即翻译整个表单。)

ref class LanguageSwitcher
{
public:
   /// <summary>
   /// Change language at runtime in the specified form
   /// </summary>
   [System::Runtime::CompilerServices::Extension]
   static void SetLanguage( Form ^form, CultureInfo ^lang )
   {
      //Set the language in the application
      System::Threading::Thread::CurrentThread->CurrentUICulture = lang;

      ComponentResourceManager ^resources = gcnew ComponentResourceManager( form->GetType() );

      ApplyResourceToControl( resources, form->MainMenuStrip, lang );
      ApplyResourceToControl( resources, form, lang );

      form->Text = resources->GetString( "$this.Text", lang );
   }
private:
   static void ApplyResourceToControl( ComponentResourceManager ^resources, Control ^control, CultureInfo ^lang )
   {
      for each( Control ^c in control->Controls )
      {
         ApplyResourceToControl( resources, c, lang );
         String ^text = resources->GetString( c->Name + ".Text", lang );
         if( text != nullptr )
            c->Text = text;
      }
   }

   static void ApplyResourceToControl( ComponentResourceManager ^resources, MenuStrip ^menu, CultureInfo ^lang )
   {
      if(menu != nullptr)
         for each( ToolStripItem ^m in menu->Items )
         {
            String ^text = resources->GetString( m->Name + ".Text", lang );
            if( text != nullptr )
               m->Text = text;
         }
    }
};

这是它的使用方式:

System::Globalization::CultureInfo^ lang = cli::safe_cast<System::Globalization::CultureInfo^ >(langCombo->SelectedItem);
LanguageSwitcher::SetLanguage(this,lang);

希望这可以帮助!

于 2012-10-24T13:13:53.340 回答