1、新建一个WinForm程序(在中文版的Windows下),如下,添加1个Button和1个Label

WinForm 国际化开发一例_自动加载

设置Form1的localizable属性为True(Form1的properties里的Design->Localizable=True);

 

2、Add一个Folder,命名为Resources,表示将来所有的资源文件都放在其下。再Resources中Add一个New Item,选择General下的Resources File,命名为Resource1.resx。添加字符串如下

WinForm 国际化开发一例_自动加载_02

这里在字符串前用[CN]表示中文;

 

3、添加其他语言版本的资源文件,依次命名为Resource1.en-US.resx,Resource1.ja-JP.resx。只要满足这种命名方式,WinForm会自动根据不同国家版本的操作系统选择对应的资源文件进行加载。想想这种自动的方式,减少了多少手工根据locale编写的if代码

WinForm 国际化开发一例_microsoft_03

字符串前的[JP]表示日文,[EN]表示英文;

 

4、打开Form1.Designer.cs文件,展开其中的WindowsForm Designer generated code,如下

WinForm 国际化开发一例_开发版_04

如果Form1的localizable属性为false,将会生成下图这样的代码

WinForm 国际化开发一例_字符串_05

可见非国际化的Form,生成的代码中就含有hardcode。下面我们在做了国际化的代码中添加来自于资源的字符串。

 

5、将资源文件中的字符串添加到对应的Button1, Label1,Form1

this.button1.Text= Resources.Resource1.BtnText;

this.label1.Text= Resources.Resource1.LabelText;

this.Text =Resources.Resource1.FormText;

Resources是我们上面添加的Folder,Resource1是当前系统下开发版的资源文件。只要这样就可以,当我们把程序拿到其它语言版操作系统下运行时,会自动加载对应的资源文件。比如将这个程序拿到日文操作系统下运行,不需要修改代码,自动加载Resources.Resource1.ja-JP.BtnText到button1显示;

 

6、在中文、日文、英文Win8系统下运行同一个程序时的效果

WinForm 国际化开发一例_自动加载_06

至此,国际化开发完毕。

 

Attention

不知道WinForm程序根据什么来选择对应语言的资源文件,在同一个OS下改了system locale都不能切换资源,非得运行在特定语言的OS下才行。

 

参考资料



[1] Article about Winform I18n .​​http://www.codeproject.com/Articles/43360/Globalization-Internationalization-I18N-and-Locali#_rating​

[2] MS resourcemanager I18nexample . ​​http://msdn.microsoft.com/zh-cn/library/system.resources.resourcemanager(v=vs.80).aspx​

[3] cultureinfo class. ​​http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo.aspx​


 


​​