Demo目的:实现界面的多语言国际化
编程语言:C#
步骤如下:
1、建立一个基于窗体的c#应用程序,在Form1窗体中添加控件label1,label2,button1;
2、添加资源文件Resource1.zh-CN.resx,Resource1.zh-TW.resx,Resource1.en-US.resx;(方法:右键项目->添加
类->资源文件)
3、
然后在资源文件resxResource1.zh-CN.resx中添加:
Form1 测试窗体
Form1label1 用户名
Form1label2 密码
Form1button1 保存(&S)
在资源文件resxResource1.en-US.resx中添加:
Form1 TestForm
Form1label1 User Name
Form1label2 Passwrod
Form1button1 &Save
在资源文件Resource1.zh-TW.resx 略
注:有点类似于VC里的字符串表,每一个文件中字符串要相同,且命名方式都是“窗体名+控件名”,要注意C#是区分大小写的喔。窗体名和控件名必须跟属性窗口中定义的一致,C#编程简单,但是相对C++太不底层了,所以不灵活,很傻瓜,咔咔~
4、SelectLanguage类 封装实现多语言
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Resources;
using System.Threading;
using System.Globalization;
using System.Windows.Forms;
namespace TestLanguage
{
public class SelectLanguage
{
public SelectLanguage()
{
}
private string formName;
public ResourceManager GetCurrentCulture()
{
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("zh-TW"); //中文台湾;若参数是en-US则是英语
ResourceManager rm = new ResourceManager("TestLanguage.Resource.Resource1", Assembly.GetExecutingAssembly()); //TestLanguage:工程名,Resource:文件夹名,Resource1:资源文件名return rm;
}
public System.Drawing.Bitmap GetImage(string strObjectId)
{
ResourceManager rm = GetCurrentCulture();
object obj = rm.GetObject(strObjectId);
return (System.Drawing.Bitmap)obj;
}
public string getMsg(string strId)
{
string currentLanguage = "";
try
{
ResourceManager rm = GetCurrentCulture();
CultureInfo ci = Thread.CurrentThread.CurrentCulture;
currentLanguage = rm.GetString(strId, ci); //ci是选择的语言,本程序是在代码中固化了语言(GetCurrentCulture函数第一行代码),实际项目应用此参数可能来源于界面某下拉列表框
}
catch
{
currentLanguage = "Cannot Found:" + strId + " , Please Add it to Resource File.";
}
return currentLanguage;
}
public void SetLanguage(System.Windows.Forms.Control control)
{
//MessageBox.Show(control.GetType().BaseType.Name);
if (control.GetType().BaseType.Name == "Form")
{
formName = control.Name;
control.Text = getMsg(control.Name);
}
for (int i = 0; i < control.Controls.Count; i++)
{
//MessageBox.Show(control.Controls[i].GetType().Name + "-" + control.Controls[i].Name);
switch (control.Controls[i].GetType().Name)
{
case "Label":
case "Button":
case "CheckBox":
case "LinkLabel":
control.Controls[i].Text = getMsg(formName + control.Controls[i].Name);
break;
case "Panel":
SetLanguage(control.Controls[i]);
break;
case "TabControl":
TabControl tbc = (TabControl)control.Controls[i];
for (int j = 0; j < tbc.TabCount; j++)
{
tbc.TabPages[j].Text = getMsg(formName + tbc.TabPages[j].Name);
SetLanguage(tbc.TabPages[j]);
}
break;
default:
break;
}
}
}
}
}