C# 中英文切换

简介:

        一个项目如果要面对外国的客户时,需要语言切换。本文使用XML,XML是可扩展标记语言(Extensible Markup Language)的缩写,仅用于存储数据。

       代码下载链接。

 

中文
英文

 

1.使用

  1. 新建三个文件。文件的路径和格式需要和MultiLanguage类对应。
  2. readme.xml存放的是记录选择的语言类型。
  3. Chinese.xml是窗体控件对应的中文。
  4. English.xml是窗体控件对应的英文。
三个文件
Chinese.xml

 

English.xml
readme.xml

 

2. 原理

  1. 窗体的Name,需要根据当前窗体的实际名称进行更改。不管是任何窗体,按照如下格式即可。
  2. 控件的Name和Text,根据实际情况填写。不管是任何控件,按照如何格式即可。
  <Form Name="Form1">	
    <Controls name="chineseToolStripMenuItem" text="中文" ></Controls>	
    <Controls name="englishToolStripMenuItem" text="英文" ></Controls>		
    <Controls name="languageToolStripMenuItem" text="语言" ></Controls>	
  </Form>

 

3.代码

  1. 读取readme.xml的语言类型,加载对应的语言配置文件。
  2. 通过菜单的Click事件,选择语言类型。
  3. MultiLanguage类展示。
  • 加载

        private void Form1_Load(object sender, EventArgs e)
        {
            LanguageInit();
        }
        private void LanguageInit()
        {
            string lang = MultiLanguage.GetDefaultLanguage();
            LanguageSwitch(this, lang);
        }
  • 选择
        private void languageToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem menu = sender as ToolStripMenuItem;
            string lang = "";
            if (menu == chineseToolStripMenuItem)
            {
                lang = Enum.GetName(typeof(enumLanguage), 0);
            }
            else if (menu == englishToolStripMenuItem)
            {
                lang = Enum.GetName(typeof(enumLanguage), 1);
            }
            LanguageSwitch(this, lang);
        }

        private void LanguageSwitch(Form form, string lang)
        {

            if (!MultiLanguage.LoadLanguage(form, lang))
            {
                return;
            }
            MultiLanguage.SetDefaultLanguage(lang);
            if (lang == Enum.GetName(typeof(enumLanguage), 0))
            {
                chineseToolStripMenuItem.Checked = true;
                englishToolStripMenuItem.Checked = false;
            }
            else if (lang == Enum.GetName(typeof(enumLanguage), 1))
            {
                chineseToolStripMenuItem.Checked = false;
                englishToolStripMenuItem.Checked = true;
            }
        }
  • MultiLanguage类 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Data;
using System.Xml;
using System.Xml.Linq;

namespace 中英文切换
{
    public enum enumLanguage
    {
        Chinese,
        English,
    }

    class MultiLanguage
    {
              //当前默认语言
        public static string DefaultLanguage = "ChineseSimplified";
        private static List<string> ListMenu = new List<string>();
        private static Dictionary<string,ToolStripMenuItem> DicMenu = new Dictionary<string,ToolStripMenuItem>();
         /// <summary>
         /// 读取当前默认语言
          /// </summary>
        /// <returns>当前默认语言</returns>
         public static string GetDefaultLanguage()
         {
              string defaultLanguage = "ChineseSimplified";

              XDocument document = new XDocument();
              string strRead = "Languages/" + "readme" + ".xml";
              string strFile = System.Windows.Forms.Application.StartupPath + "/" + strRead;
              if (!System.IO.File.Exists(strFile))
              {
                  defaultLanguage = string.Empty;
                  return defaultLanguage;
              }

              document = XDocument.Load(strRead);
             
              XElement root1 = document.Root;
              defaultLanguage = root1.FirstAttribute.Value;

             
             return defaultLanguage;
         }

        /// <summary>
       /// 修改默认语言
        /// </summary>
         /// <param name="lang">待设置默认语言</param>
         public static void SetDefaultLanguage(string lang)
        {
             DataSet ds = new DataSet();

             XDocument document = new XDocument();
             document = XDocument.Load("Languages/" + "readme" + ".xml");
             XElement root = document.Root;
             root.FirstAttribute.Value = lang;
             document.Save("Languages/" + "readme" + ".xml");
             
         }

        private static void EnumerateMenu(ToolStripMenuItem item)
         {
             foreach (ToolStripMenuItem subItem in item.DropDownItems)
             {
                 ListMenu.Add(subItem.Name);
                 DicMenu.Add(subItem.Name,subItem);
                 EnumerateMenu(subItem);
            }
         }

        /// <summary>
         /// 加载语言
         /// </summary>
        /// <param name="form">加载语言的窗口</param>
        public static bool LoadLanguage(Form form, string language)
         {
             if (form == null || form.IsDisposed)
             {
                 return false;
            }
             if (string.IsNullOrEmpty(language))
             {
                 return false;
             }
            //根据用户选择的语言获得表的显示文字 
            Hashtable hashText = ReadXMLText(form.Name, language);
            Hashtable hashHeaderText = ReadXMLHeaderText(form.Name, language);
            if (hashText == null)
            {
                return false;
           }
             //获取当前窗口的所有控件
             Control.ControlCollection sonControls = form.Controls;
      
           try
           {
               DicMenu.Clear();
               ListMenu.Clear();
                 MenuStrip menu = form.MainMenuStrip;
                 if (menu != null)
                 {
                     foreach (ToolStripMenuItem item in menu.Items)
                     {
                         ListMenu.Add(item.Name);
                         DicMenu.Add(item.Name, item);
                         EnumerateMenu(item);
                     }
                 }
     
                   var result = from pair in DicMenu orderby pair.Key select pair;
                   foreach (KeyValuePair<string, ToolStripMenuItem> pair in result)
                   {
                       if (hashText.Contains(pair.Key))
                       {
                           pair.Value.Text = (string)hashText[pair.Key];
                       }
                   }


                     //遍历所有控件
                     foreach (Control control in sonControls)
                     {
                         if (control.GetType() == typeof(Panel))     //Panel
                         {
                             GetSetSubControls(control.Controls, hashText, hashHeaderText);
                         }
                         else if (control.GetType() == typeof(GroupBox))     //GroupBox
                         {
                             GetSetSubControls(control.Controls, hashText, hashHeaderText);
                         }
                         else if (control.GetType() == typeof(TabControl))       //TabControl
                         {
                             GetSetSubControls(control.Controls, hashText, hashHeaderText);
                         }
                         else if (control.GetType() == typeof(TabPage))      //TabPage
                         {
                             GetSetSubControls(control.Controls, hashText, hashHeaderText);
                         }
                         else if (control.GetType() == typeof(TableLayoutPanel))     //TableLayoutPanel
                         {
                             GetSetSubControls(control.Controls, hashText, hashHeaderText);
                         }
                         else if (control.GetType() == typeof(DataGridView))     //DataGridView
                         {
                             GetSetHeaderCell((DataGridView)control, hashHeaderText);
                         }
                         else if (control.GetType() == typeof(Button))     //Button
                         {
                             GetSetSubControls(control.Controls, hashText, hashHeaderText);
                         }
                         else if (control.GetType() == typeof(ToolStripMenuItem))     //menu
                         {
                             GetSetSubControls(control.Controls, hashText, hashHeaderText);
                         }

                         if (hashText.Contains(control.Name))
                         {
                             control.Text = (string)hashText[control.Name];
                         }

                     }
                //如果找到了控件,就将对应的名字赋值过去
                 if (hashText.Contains(form.Name))
                 {
                     form.Text = (string)hashText[form.Name];
                 }
             }
            catch (Exception ex)
           {
                string s = ex.ToString();
                return false;
             }
             return true;
         }
 
 
         /// <summary>
        /// 获取并设置控件中的子控件
         /// </summary>
         /// <param name="controls">父控件</param>
        /// <param name="hashResult">哈希表</param>
         private static void GetSetSubControls(Control.ControlCollection controls, Hashtable hashText, Hashtable hashHeaderText)
         {
            try
             {
                 foreach (Control control in controls)
                 {
                     if (control.GetType() == typeof(Panel))     //Panel
                     {
                         GetSetSubControls(control.Controls, hashText, hashHeaderText);
                     }
                     else if (control.GetType() == typeof(GroupBox))     //GroupBox
                     {
                         GetSetSubControls(control.Controls, hashText, hashHeaderText);
                     }
                     else if (control.GetType() == typeof(TabControl))       //TabControl
                     {
                         GetSetSubControls(control.Controls, hashText, hashHeaderText);
                     }
                     else if (control.GetType() == typeof(TabPage))      //TabPage
                     {
                         GetSetSubControls(control.Controls, hashText, hashHeaderText);
                     }
                     else if (control.GetType() == typeof(TableLayoutPanel))     //TableLayoutPanel
                     {
                         GetSetSubControls(control.Controls, hashText, hashHeaderText);
                     }
                     else if (control.GetType() == typeof(DataGridView))
                     {
                         GetSetHeaderCell((DataGridView)control, hashHeaderText);
                     }
                     else if (control.GetType() == typeof(Button))     //Button
                     {
                         GetSetSubControls(control.Controls, hashText, hashHeaderText);
                     }
    
                    if (hashText.Contains(control.Name))
                    {
                         control.Text = (string)hashText[control.Name];
                     }
                 }
             }
             catch (Exception ex)
            {
                 throw new Exception(ex.Message);
             }
         }

         /// <summary>
        /// 从XML文件中读取需要修改Text的內容
         /// </summary>
        /// <param name="frmName">窗口名,用于获取对应窗口的那部分内容</param>
         /// <param name="xmlName">目标语言</param>
         /// <returns></returns>
        private static Hashtable ReadXMLText(string frmName, string xmlName)
         {
             try
             {
                 Hashtable hashResult = new Hashtable();
                 XmlReader reader = null;
                 //判断是否存在该语言的配置文件
                 if (!(new System.IO.FileInfo("Languages/" + xmlName + ".xml")).Exists)
                {
                    return null;
                }
                else
                 {
                    reader = new XmlTextReader("Languages/" + xmlName + ".xml");
                }

                 XDocument document = new XDocument();
                 document = XDocument.Load("Languages/" + xmlName + ".xml");

                 var classData = (from n in document.Root.Elements("Form")
                                  where n.Attribute("Name").Value == frmName
                                  select n).ToList();
                 foreach (var item in classData.Elements("Controls"))
                 {
                     XElement xe = (XElement)item;
                     XAttribute xName = xe.Attribute("name");
                     XAttribute xText = xe.Attribute("text");
                     string name = xName.Value;
                     string text = xText.Value;
                     if (name != null && text != null)
                     {
                         hashResult.Add(name, text);
                     }


                     
                 }

                
                reader.Close();
                // reader.Dispose();
                return hashResult;
             }
             catch
             {
                return null;
            }
        }
 
         /// <summary>
         /// 从XML文件中读取需要修改HeaderText的內容
        /// </summary>
         /// <param name="frmName">窗口名,用于获取对应窗口的那部分内容</param>
         /// <param name="xmlName">目标语言</param>
        /// <returns></returns>
         private static Hashtable ReadXMLHeaderText(string frmName, string xmlName)
         {
             try
            {
                 Hashtable hashResult = new Hashtable();
                 XmlReader reader = null;
                //判断是否存在该语言的配置文件
                 if (!(new System.IO.FileInfo("Languages/" + xmlName + ".xml")).Exists)
                 {
                     return null;
                 }
                else
                 {
                     reader = new XmlTextReader("Languages/" + xmlName + ".xml");
                 }

                 XDocument document = new XDocument();
                 document = XDocument.Load("Languages/" + xmlName + ".xml");

                 var classData = (from n in document.Root.Elements("Form")
                                  where n.Attribute("Name").Value == frmName
                                  select n).ToList();
                 foreach (var item in classData.Elements("Controls"))
                 {
                     XElement xe = (XElement)item;
                     XAttribute xName = xe.Attribute("name");
                     XAttribute xText = xe.Attribute("text");
                     string name = xName.Value;
                     string text = xText.Value;
                     if (name != null && text != null)
                     {
                         hashResult.Add(name, text);
                     }


                 }
                reader.Close();
                //reader.Dispose();
                return hashResult;
            }
             catch
            {
                return null;
            }
         }
 
         /// <summary>
         /// 获取并设置DataGridView的列头
         /// </summary>
        /// <param name="dataGridView">DataGridView名</param>
         /// <param name="hashResult">哈希表</param>
        private static void GetSetHeaderCell(DataGridView dataGridView, Hashtable hashHeaderText)
         {
             foreach (DataGridViewColumn column in dataGridView.Columns)
             {
                if (hashHeaderText.Contains(column.Name.ToLower()))
                 {
                     column.HeaderText = (string)hashHeaderText[column.Name.ToLower()];
                 }
             }
         }
    }
}

 

  • 8
    点赞
  • 48
    收藏
    觉得还不错? 一键收藏
  • 16
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 16
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值