我們須具備一個觀念:應用程式的文字都是一種資源,切換顯示文字只不過是在切換資源。所以,在多語言應用程式的開發上,要注意的是以下幾點:
- 不同的語言內容,定義在各自的資源檔中。
- 程式中使用索引鍵 (Key) 取用文字。
- 設定系統作用中的語系,讓系統自動取得正確的文字語言。
以下文章已詳細說明基本的使用過程:
MSDN: 逐步解說:將 Windows Form 當地語系化
http://msdn.microsoft.com/zh-tw/library/y99d1cd3(v=vs.110).aspx
不過文中所說明的方法,只能在程式啟動時,決定一種要顯示的語言,如果我們必須在執行時期即時切換語言的話,要怎麼作呢?
範例:按下按鈕,即時變更顯示語言。
程式碼:
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);
}
}
}
}

