一般来说,Winform窗体里面Label、Button等控件需要不同的语言来表示。我想通过约束资源文件中对应控件名的名称,来到达简化编程的目的。具体方法如下:我先抛块砖,有玉的尽量向我砸过来。
我们在Resource文件中建立几个资源文件如:Resource1.zh-CN.resx,Resource1.zh-TW.resx,Resource1.en-US.resx。
然后在资源文件resxResource1.zh-CN.resx中添加:Form1 测试窗体Form1label1 用户名Form1label2 密码Form1button1 保存(&S)
在资源文件resxResource1.en-US.resx中添加:Form1 TestFormForm1label1 User NameForm1label2 PasswrodForm1button1 &Save
在资源文件Resource1.zh-TW.resx 略
建立Form1,在上面放几个控件label1,label2,button1。在Form1的构造函数或Form1_Load事件中添加:(new SelectLanguage()).SetLanguage(this);,就可以实现Winform窗体的国际化,相当的简单方便。要实现国际化的控件在资源文件中命名规则是: Form窗体 + 控件名称。
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"); ResourceManager rm = new ResourceManager("TestLanguage.Resource.Resource1", Assembly.GetExecutingAssembly());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); }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; } } } }}去掉//Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("zh-TW");的注释,或修改成//Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");你将看到不同的效果。
转载于:https://www.cnblogs.com/hengbo/archive/2009/04/16/2232502.html
相关资源:数据结构—成绩单生成器