winform 中英文切换
我们可以通过一个按钮或者单选框之类的控件来触发切换事件
这里我用按钮点击事件实现切换效果
界面如下:
1.新建两个资源文件,一个中文,一个英文
下面是资源文件的具体内容
注意: 这里不能错,否则无效,要把项目名拼写注意一下。
2.详细代码实现
using System.ComponentModel;
using System.Globalization;
namespace multiLanguage
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnZh_Click(object sender, EventArgs e)
{
if (Thread.CurrentThread.CurrentCulture.Name == "zh")
return;
Thread.CurrentThread.CurrentCulture = new CultureInfo("zh");//中文
ApplyResource(this);//传入当前的界面
}
private void btnEn_Click(object sender, EventArgs e)
{
if (Thread.CurrentThread.CurrentCulture.Name == "en")
return;
Thread.CurrentThread.CurrentCulture = new CultureInfo("en");//英文
ApplyResource(this);//传入当前的界面
}
ComponentResourceManager crm;
public void ApplyResource(Control control)
{
switch (Thread.CurrentThread.CurrentCulture.Name)
{
case "en":
crm = new ComponentResourceManager(typeof(Resource.Resource_en));
break;
case "zh":
crm = new ComponentResourceManager(typeof(Resource.Resource_zh));
break;
default:
crm = new ComponentResourceManager(typeof(Resource.Resource_zh));
break;
}
applyControl(control.GetType().Name, control);//调用
}
//递归应用到控件
private void applyControl(string topName, Control control)
{
foreach (Control ctl in control.Controls)
{
crm.ApplyResources(ctl, topName + "." + ctl.Name, Thread.CurrentThread.CurrentCulture);
if (ctl.HasChildren)
{
applyControl(topName, ctl);
}
}
}
}
}
点击中文按钮
点击英文按钮
代码中对相同资源做了判断,要是不改变,就不会刷新,变更了资源才会刷新界面。
3. 配置文件
添加一个配置文件
在程序入口进行读取
using Microsoft.Extensions.Configuration;
using System.Globalization;
namespace multiLanguage
{
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
ApplicationConfiguration.Initialize();
IConfiguration configuration = new ConfigurationBuilder()
.SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.Build();
string setting1 = configuration["AppSettings:CultureInfo"]??"zh";
Thread.CurrentThread.CurrentUICulture = new CultureInfo(setting1);
Application.Run(new Form1());
}
}
}
这样就实现了用配置文件控制输出了。
在这里需要注意,配置文件记得选上如果新则复制
,.net core的环境下不要用App.Config
了,ConfigurationManager.AppSettings["Setting1"];
这个方法不好使了,这个是.net framework环境下用的了,需要使用appsetting.json
。