2014年6月25日 星期三

How to change Windows Form language at runtime

When we were developed an oversea product, it must exist a requirement that switch UI language at runtime. Windows Form of .Net has already provide a localization framework for you, it's very easy to complete a multi-language application if you follow the correct way. The framework is also allow you to switch to specified language at runtime.

We must have a concept, the texts of an application are kinds of resource, change the display language is just change the resource we use. For this reason,  the following notes are useful for developing a multi-language application.
  1. Content of different languages are defined in their specified resource file.
  2. Use index key to retrieve the text in program.
  3. Set the current language (culture) to get the text with correct language.
The MSDN article has explained localization steps of a windows form application very clearly:

Walkthrough: Localizing Windows Forms

http://msdn.microsoft.com/en-us/library/y99d1cd3(v=vs.110).aspx

But the method of the article is just workable in the beginning of application, we still don't know how to change the language at runtime. I have a solution for this issue.

Example: Press the button and change to corresponding language.



Source code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void BtnChinese_Click(object sender, EventArgs e)
        {
            ChangeLanguage("zh-TW");
        }

        private void BtnEnglish_Click(object sender, EventArgs e)
        {
            ChangeLanguage("en-US");
        }


        private void ChangeLanguage(string lang)
        {
            Thread.CurrentThread.CurrentUICulture = new CultureInfo(lang);
            ComponentResourceManager res = new ComponentResourceManager(typeof(Form1));
            ChangeLanguage(this, res);
        }

        private void ChangeLanguage(Control ctrl, ComponentResourceManager res)
        {
            res.ApplyResources(ctrl, ctrl.Name, Thread.CurrentThread.CurrentUICulture);
            foreach (Control c in ctrl.Controls)
            {
                ChangeLanguage(c, res);
            }
        }
    }
}