November 26, 2017

C# Winforms - How to use localized strings/translations using ResourceManager

In this post I will explain how to implement localization in Windows Forms Application using ResourceManager class. We will see an example application with Login form, and change the strings/labels with two different locales (in this example I am using English and Arabic locales). So lets start with this sample Login form.

We want to see the form display with English locale similar to the following screenshot

And with Arabic locale, the form should display similar to this screenshot

First we have to create separate resource files for separate locales (English and Arabic in this example)

Here is the resource file for English locale Messages.en.resx.

And here is the resource file for Arabic locale

Note that the resource file names are ended with .en and .ar and then the actual file extension .resx. Similarly if you want to create resource files for any other language, you have to create separate resource file with correct file name ending with .[locale-name]

In this example I have placed these two resources files in MyResources folder, solution explorer seems like this:

We have written the labels translations in resource files. Its time to write real C# code to use these resource files and display the target translated labels on corresponding controls. For this we are using ResourceManager class found in namespace System.Resources.

Lets create a function which accepts the lang argument, and set labels/controls texts with corresponding string translations from resource files by passing the target CultureInfo argument. To get the desired translated string, we are using helper method rm.GetString().

 private void ChangeLang(string lang)
  CultureInfo ci = new CultureInfo(lang);

  System.Resources.ResourceManager rm = new System.Resources.ResourceManager("WindowsFormsApplication1.MyResources.Messages", typeof(Form1).Assembly);
  lblUserName.Text = rm.GetString("UserName", ci);
  lblPassword.Text = rm.GetString("Password", ci);
  btnLogin.Text = rm.GetString("Login", ci);
  rbEnglish.Text = rm.GetString("English", ci);
  rbArabic.Text = rm.GetString("Arabic", ci);
  this.Text = rm.GetString("Authentication", ci);

Note that ResourceManager constructor accepts argument as the complete assembly name, folder, and resource file name concatenating with dots ("WindowsFormsApplication1.MyResources.Messages" in this case).

Now run the application and you should be able to see the login form displaying the strings/translations based on selected locales.

I hope you have found this article helpful, I welcome your comments and suggestions to analyze this technique, and find if there is any better alternative for implementing localization.

No comments:

Post a Comment