分享兩種實現Winform程式的多語言支援的解決方案

夢在旅途發表於2016-09-26

因公司業務需要,需要將原有的ERP系統加上支援繁體語言,但不能改變原有的編碼方式,即:普通程式設計師感受不到編碼有什麼不同。經過我與幾個同事的多番溝通,確定了以下兩種方案:

方案一:在窗體基類中每次載入並顯示窗體時,會自動遞迴遍歷含文字顯示的控制元件(Button,CheckBox,GroupBox,Label,LinkLabel,TextBox,StatusStrip,TabPage,ToolStrip,RadioButton,DateTimePicker,DataGridView,CheckedListBox,TreeView,MenuStrip),並根據不同的控制元件型別的文字屬性呼叫簡繁轉換方法進行轉換並重新設定新的相應文字屬性的內容(比如:繁體內容)

優點:編碼簡單,對普通程式設計師的編碼無影響(除窗體類的基類由Form類變成MyStyleFormBase類);

缺點:因每次開啟窗體都需要遍歷控制元件並進行簡繁轉換,如果介面上的控制元件較多,則可能導致開啟窗體較慢,影響使用者體驗,且子控制元件的文字內容改變時需程式設計師手動通知,無法自動感知並轉換。

具體實現思路如下:

一.對Form類進行二次封裝(繼承),定義一個MyStyleFormBase類,並在裡面加入每次載入並顯示窗體型別時,會自動遞迴遍歷含文字顯示的控制元件,並根據不同的控制元件型別的文字屬性呼叫簡繁轉換方法進行轉換並重新設定新的相應文字屬性的內容,這樣當所有的窗體都繼承MyStyleFormBase類時,均預設就實現了遍歷與轉換的過程,程式設計師無需再次編碼,甚至都無需知道存在遍歷與轉換的過程,從而提高了程式碼的複用性,具體程式碼如下:

    public class MyStyleFormBase : Form
    {
        public MyStyleFormBase()
        {
            if (!Thread.CurrentThread.CurrentUICulture.Name.Equals("zh-CHS", StringComparison.OrdinalIgnoreCase)) //如果是簡體,則無需轉換
            {
                base.TextChanged += MyStyleFormBase_TextChanged;
                base.Shown += MyStyleFormBase_Shown;
            }
        }

        private void MyStyleFormBase_TextChanged(object sender, EventArgs e)
        {
            this.Text = LanguageHelper.GetLanguageText(this.Text);
        }

        private void MyStyleFormBase_Shown(object sender, EventArgs e)
        {
            LanguageHelper.SetControlLanguageText(this);
            base.ControlAdded += MyStyleFormBase_ControlAdded;
        }

        private void MyStyleFormBase_ControlAdded(object sender, ControlEventArgs e)
        {
            LanguageHelper.SetControlLanguageText(e.Control);
        }

        /// <summary>
        /// 強制通知子控制元件改變訊息
        /// </summary>
        /// <param name="target"></param>
        protected virtual void PerformChildrenChange(Control target)
        {
            LanguageHelper.SetControlLanguageText(target);
        }

        /// <summary>
        /// 彈出訊息框
        /// </summary>
        /// <param name="text"></param>
        /// <param name="caption"></param>
        /// <param name="buttons"></param>
        /// <param name="icon"></param>
        /// <param name="defaultButton"></param>
        /// <returns></returns>
        protected DialogResult MessageBoxShow(string text, string caption, MessageBoxButtons buttons = MessageBoxButtons.OK, MessageBoxIcon icon = MessageBoxIcon.None, MessageBoxDefaultButton defaultButton = MessageBoxDefaultButton.Button1)
        {
            return MessageBox.Show(LanguageHelper.GetLanguageText(text), LanguageHelper.GetLanguageText(caption), buttons, icon, defaultButton);
        }
    }

程式碼邏輯簡要說明:

1.噹噹前UI的文化區域不為中文簡體時(因為本程式本身都是基於簡體開發的),就訂閱窗體顯示事件Shown及窗體標題改變事件TextChanged,作用:當窗體顯示時,則會遍歷控制元件並轉換為繁體,當標題的文字改變時,也會自動轉換為繁體;

2.當窗體顯示後訂閱窗體的控制元件增加事件ControlAdded,作用:當窗體顯示後,若後續存在程式碼增加控制元件時,會自動將控制元件及其子控制元件進行繁體的轉換,保證一個都不漏;

3.增加一個訊息提示框方法,目的是彈出訊息視窗前能夠將簡體文字轉換成繁體文字;

4.增加一個強制通知子控制元件改變訊息的方法PerformChildrenChange,當某個控制元件的文字內容或增加子控制元件發生時,由於窗體本身無法捕獲到,故需要呼叫該方法來遍歷與轉換子控制元件的文字內容;(感覺這裡不太好,但目前沒有更好的辦法,如果大家有更好的辦法,歡迎留言評論)

 二、LanguageHelper:語方轉換公共類(目前僅支援簡繁轉換,依賴於:ChineseConverter.dll)程式碼如下:

    public class LanguageHelper
    {
        #region 簡繁體轉換
        /// <summary>
        /// 內容的語言轉化
        /// </summary>
        /// <param name="parent"></param>
        public static void SetControlLanguageText(System.Windows.Forms.Control parent)
        {
            if (parent.HasChildren)
            {
                foreach (System.Windows.Forms.Control ctrl in parent.Controls)
                {
                    SetContainerLanguage(ctrl);
                }
            }
            else
            {
                SetLanguage(parent);
            }
        }
        #endregion
        #region 控制元件簡繁體語言轉換

        /// <summary>
        /// 設定容器類控制元件的語言
        /// </summary>
        /// <param name="ctrl"></param>
        /// <returns></returns>
        private static void SetContainerLanguage(System.Windows.Forms.Control ctrl)
        {
            if (ctrl is DataGridView)
            {
                try
                {
                    DataGridView dataGridView = (DataGridView)ctrl;
                    foreach (DataGridViewColumn dgvc in dataGridView.Columns)
                    {
                        try
                        {
                            if (dgvc.HeaderText.ToString() != "" && dgvc.Visible)
                            {
                                dgvc.HeaderText = GetLanguageText(dgvc.HeaderText);
                            }
                        }
                        catch
                        {
                        }
                    }
                }
                catch (Exception)
                { }
            }
            if (ctrl is MenuStrip)
            {
                MenuStrip menuStrip = (MenuStrip)ctrl;
                foreach (ToolStripMenuItem toolItem in menuStrip.Items)
                {
                    try
                    {
                        toolItem.Text = GetLanguageText(toolItem.Text);
                    }
                    catch (Exception)
                    {
                    }
                    finally
                    {
                        if (toolItem.DropDownItems.Count > 0)
                        {
                            GetItemText(toolItem);
                        }
                    }
                }
            }
            else if (ctrl is TreeView)
            {
                TreeView treeView = (TreeView)ctrl;
                foreach (TreeNode node in treeView.Nodes)
                {
                    try
                    {
                        node.Text = GetLanguageText(node.Text);
                    }
                    catch (Exception)
                    {
                    }
                    finally
                    {
                        if (node.Nodes.Count > 0)
                        {
                            GetNodeText(node);
                        }
                    }
                }
            }
            else if (ctrl is TabControl)
            {
                TabControl tabCtrl = (TabControl)ctrl;
                try
                {
                    foreach (TabPage tabPage in tabCtrl.TabPages)
                    {
                        tabPage.Text = GetLanguageText(tabPage.Text);
                    }
                }
                catch (Exception)
                {
                }
            }
            else if (ctrl is StatusStrip)
            {
                StatusStrip statusStrip = (StatusStrip)ctrl;
                foreach (ToolStripItem toolItem in statusStrip.Items)
                {
                    try
                    {
                        toolItem.Text = GetLanguageText(toolItem.Text);
                    }
                    catch (Exception)
                    {
                    }
                    finally
                    {
                        ToolStripDropDownButton tsDDBtn = toolItem as ToolStripDropDownButton;
                        if (tsDDBtn != null && tsDDBtn.DropDownItems.Count > 0)
                        {
                            GetItemText(tsDDBtn);
                        }
                    }
                }
            }
            else if (ctrl is ToolStrip)
            {
                ToolStrip statusStrip = (ToolStrip)ctrl;
                foreach (ToolStripItem toolItem in statusStrip.Items)
                {
                    try
                    {
                        toolItem.Text = GetLanguageText(toolItem.Text);
                    }
                    catch (Exception)
                    {
                    }
                }
            }
            else if (ctrl is CheckedListBox)
            {
                CheckedListBox chkListBox = (CheckedListBox)ctrl;
                try
                {
                    for (int n = 0; n < chkListBox.Items.Count; n++)
                    {
                        chkListBox.Items[n] = GetLanguageText(chkListBox.Items[n].ToString());
                    }
                }
                catch (Exception)
                { }
            }

            if (ctrl.HasChildren)
            {
                foreach (System.Windows.Forms.Control c in ctrl.Controls)
                {
                    SetContainerLanguage(c);
                }
            }
            else
            {
                SetLanguage(ctrl);
            }

        }
        /// <summary>
        /// 設定普通控制元件的語言
        /// </summary>
        /// <param name="ctrl"></param>
        /// <returns></returns>
        private static void SetLanguage(System.Windows.Forms.Control ctrl)
        {
            if (true)
            {
                if (ctrl is CheckBox)
                {
                    CheckBox checkBox = (CheckBox)ctrl;
                    try
                    {
                        checkBox.Text = GetLanguageText(checkBox.Text);
                    }
                    catch (Exception)
                    {
                    }
                }
                else if (ctrl is Label)
                {
                    Label label = (Label)ctrl;
                    try
                    {
                        label.Text = GetLanguageText(label.Text);
                    }
                    catch (Exception)
                    {
                    }
                }

                else if (ctrl is Button)
                {
                    Button button = (Button)ctrl;
                    try
                    {
                        button.Text = GetLanguageText(button.Text);
                    }
                    catch (Exception)
                    {
                    }
                }
                else if (ctrl is GroupBox)
                {
                    GroupBox groupBox = (GroupBox)ctrl;
                    try
                    {
                        groupBox.Text = GetLanguageText(groupBox.Text);
                    }
                    catch (Exception)
                    {
                    }
                }
                else if (ctrl is RadioButton)
                {
                    RadioButton radioButton = (RadioButton)ctrl;
                    try
                    {
                        radioButton.Text = GetLanguageText(radioButton.Text);
                    }
                    catch (Exception)
                    {
                    }
                }
            }

        }
        /// <summary>
        /// 遞迴轉化選單
        /// </summary>
        /// <param name="menuItem"></param>
        private static void GetItemText(ToolStripDropDownItem menuItem)
        {
            foreach (ToolStripItem toolItem in menuItem.DropDownItems)
            {
                try
                {
                    toolItem.Text = GetLanguageText(toolItem.Text);
                }
                catch (Exception)
                {
                }
                finally
                {
                    if (toolItem is ToolStripDropDownItem)
                    {
                        ToolStripDropDownItem subMenuStrip = (ToolStripDropDownItem)toolItem;
                        if (subMenuStrip.DropDownItems.Count > 0)
                        {
                            GetItemText(subMenuStrip);
                        }
                    }
                }

            }
        }
        /// <summary>
        /// 遞迴轉化樹
        /// </summary>
        /// <param name="menuItem"></param>
        private static void GetNodeText(TreeNode node)
        {

            foreach (TreeNode treeNode in node.Nodes)
            {
                try
                {
                    treeNode.Text = GetLanguageText(treeNode.Text);
                }
                catch (Exception)
                {
                }
                finally
                {
                    if (treeNode.Nodes.Count > 0)
                    {
                        GetNodeText(treeNode);
                    }
                }
            }
        }


        /// <summary>
        /// 根據語言識別符號得到轉換後的值
        /// </summary>
        /// <param name="languageFlag"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string GetLanguageText(string value)
        {
            string languageFlag = Thread.CurrentThread.CurrentUICulture.Name;
            if (string.IsNullOrWhiteSpace(value))
            {
                return value;
            }

            switch (languageFlag.ToUpper())
            {
                case "ZH-CHT":
                    {
                        return ToTraditional(value);
                    }
                default:
                    {
                        return ToSimplified(value);
                    }
            }
        }

        /// <summary> 
        /// 簡體轉換為繁體
        /// </summary> 
        /// <param name="str">簡體字</param> 
        /// <returns>繁體字</returns> 
        private static string ToTraditional(string str)
        {
            if (string.IsNullOrEmpty(str))
                return str;
            return ChineseConverter.Convert(str, ChineseConversionDirection.SimplifiedToTraditional);

        }
        /// <summary> 
        /// 繁體轉換為簡體
        /// </summary> 
        /// <param name="str">繁體字</param> 
        /// <returns>簡體字</returns> 
        private static string ToSimplified(string str)
        {
            if (string.IsNullOrEmpty(str))
                return str;
            return ChineseConverter.Convert(str, ChineseConversionDirection.TraditionalToSimplified);
        }
        #endregion

    }

該類邏輯很簡單,就是從一個父控制元件開始,遍歷所有的子控制元件,並根據不同的控制元件型別將控制元件相應的文字內容轉換成簡體或繁體,呼叫方法:SetControlLanguageText

以上二步就實現了多語言的支援了(準確的說是簡繁轉換),應用到專案中很簡單,只需將窗體預設的基類Form改成:MyStyleFormBase即可,如:public partial class FormTest : MyStyleFormBase

方案二:由控制元件依據當前區域資訊+快取語言字典直接實現各控制元件自行轉換

優點:無需遍歷,各控制元件自行根據區域資訊自支轉換,因此效率較高,對普通程式設計師的編碼無影響(除窗體類的基類由Form類變成MyStyleFormBase類外,還需要使用支援多語言的控制元件,這些控制元件均由普通控制元件二次封裝得來,保留原有的所有屬性及事件);

缺點:需將所有帶文字顯示的控制元件(如:Button,CheckBox,GroupBox,Label,LinkLabel,TextBox,StatusStrip,TabPage,ToolStrip,RadioButton,DateTimePicker,DataGridView,CheckedListBox,TreeView)均進行二次封裝,控制元件統一命名為:MyStyleXXX

 涉及的控制元件較多,編碼相對複雜;

具體實現思路如下:

一.對Form類進行二次封裝(繼承),定義一個MyStyleFormBase類,裡面加入對窗體標題進行修改時,能自動進行多語言轉換功能,具體程式碼如下:

    public partial class MyStyleFormBase : Form
    {

        public MyStyleFormBase()
        {
            base.TextChanged += MyStyleFormBase_TextChanged;
        }

        private void MyStyleFormBase_TextChanged(object sender, EventArgs e)
        {
            if (!Common.IsChsLanguage())
            {
                this.Text = LanguageHelper.GetLanguageText(this.Text);
            }
        }

        /// <summary>
        /// 彈出訊息框
        /// </summary>
        /// <param name="text"></param>
        /// <param name="caption"></param>
        /// <param name="buttons"></param>
        /// <param name="icon"></param>
        /// <param name="defaultButton"></param>
        /// <returns></returns>
        protected DialogResult MessageBoxShow(string text, string caption = "提示", MessageBoxButtons buttons = MessageBoxButtons.OK, MessageBoxIcon icon = MessageBoxIcon.None, MessageBoxDefaultButton defaultButton = MessageBoxDefaultButton.Button1)
        {
            if (!Common.IsChsLanguage())
            {
                text = LanguageHelper.GetLanguageText(text);
                caption = LanguageHelper.GetLanguageText(caption);
            }

            return MessageBox.Show(text, caption, buttons, icon, defaultButton);
        }
    }

程式碼邏輯很簡單,就是訂閱一個Form.TextChanged事件,以便當根據IsChsLanguage(判斷是否為簡體模式)判斷不是簡體時,則需進行Form.Text轉換

二.定義多語言支援普通控制元件及容器控制元件介面(IMultiLanguageControl、IMultiLanguageContainerControl),具體程式碼如下:(此處僅是為了作一個規範,支援手動設定轉換控制元件的文字內容)

    /// <summary>
    /// 支援多語言普通控制元件(無子控制元件)
    /// </summary>
    public interface IMultiLanguageControl
    {
        string DefaultLangText { get; }

        string CurrentLangText { get; set; }
    }



    /// <summary>
    /// 支援多語言容器控制元件(包含子控制元件)
    /// </summary>
    public interface IMultiLanguageContainerControl
    {
        Dictionary<object, string> DefaultLangTexts { get; }

        Dictionary<object, string> CurrentLangTexts { get; set; }

        Control this[string ctrlName] { get; set; }

        void SetItemCurrentLangText(string ctrlName, string langText);

        event EventHandler<ChildrenAddedEventArgs> ChildrenChanged;

    }



    public class ChildrenAddedEventArgs : EventArgs
    {
        public Dictionary<object, string> LangTexts { get; private set; }

        public ChildrenAddedEventArgs()
        {
            LangTexts = new Dictionary<object, string>();
        }

        public ChildrenAddedEventArgs(Dictionary<object, string> langTexts)
        {
            this.LangTexts = langTexts;
        }

        public string this[object key]
        {
            get
            {
                return LangTexts[key];
            }
            set
            {
                LangTexts[key] = value;
            }
        }
    }

三、實現支援多語言普通控制元件:基於原有標準控制元件(Button,CheckBox,GroupBox,Label,LinkLabel,TextBox,RadioButton,DateTimePicker)進行二次封裝,實現IMultiLanguageControl介面,各控制元件程式碼如下:

以下是MyStyleButton定義程式碼,MyStyleCheckBox、MyStyleGroupBox、MyStyleLabel、MyStyleLinkLabel、MyStyleTextBox、MyStyleRadioButton裡面的實現程式碼均相同

public partial class MyStyleButton : MyButton, IMultiLanguageControl
    {
        static Dictionary<string, string> LanDict = new Dictionary<string, string>();
        public MyStyleButton()
        {

        }
        public override string Text
        {
            get
            {
                if (!DesignMode && System.Threading.Thread.CurrentThread.CurrentUICulture.Name != "zh-CHS")
                {
                    if (LanDict.ContainsKey(DefaultLangText))
                    {
                        return CurrentLangText;
                    }
                    else
                    {
                        string langText = LanguageHelper.GetLanguageText(base.Text);
                        LanDict[base.Text] = langText;
                        return langText;
                    }
                }
                return base.Text;
            }
            set
            {
                base.Text = value;
            }
        }
        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public string DefaultLangText
        {
            get
            {
                return base.Text;
            }
        }
        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public string CurrentLangText
        {
            get
            {
                try
                {
                    return LanDict[DefaultLangText];
                }
                catch (Exception)
                {
                    return "";
                }
            }
            set
            {
                if (System.Threading.Thread.CurrentThread.CurrentUICulture.Name != "zh-CHS")
                {
                    if (LanDict.ContainsKey(DefaultLangText))
                    {
                        LanDict[DefaultLangText] = value;
                    }
                    else
                    {
                        LanDict.Add(DefaultLangText, value);
                    }
                }
            }
        }
    }

  

二次封裝這些控制元件的目的是:1.暴露統一的屬性,便於直接遍歷並賦值(需手動改變文字內容語言的情況);2.當文字內容發生改變時,能夠根據語言快取字典,快速直接的自我簡繁轉換,無需再次遍歷;

四、實現支援多語言容器控制元件:基於原有標準控制元件(StatusStrip,TabPage,ToolStrip,DataGridView,CheckedListBox,TreeView)進行二次封裝,實現IMultiLanguageContainerControl介面,各控制元件程式碼如下:

MyStyleDataGridView:

    public partial class MyStyleDataGridView : MyDataGridView, IMultiLanguageContainerControl
    {
        static Dictionary<string, string> LanDict = new Dictionary<string, string>();
        Dictionary<object, string> cloumnHeaderTexts = new Dictionary<object, string>();

        public MyStyleDataGridView()
        {
            cloumnHeaderTexts.Clear();
            this.CellValueChanged += MyStyleDataGridView_CellValueChanged;
        }

        private void MyStyleDataGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0)
            {
                if (System.Threading.Thread.CurrentThread.CurrentUICulture.Name != "zh-CHS")
                {
                    var headerCell = this.Columns[e.ColumnIndex].HeaderCell as DataGridViewColumnHeaderCell;

                    if (headerCell != null)
                    {
                        string headerCellValue = headerCell.Value.ToString();
                        if (LanDict.ContainsKey(headerCellValue))
                        {
                            headerCell.Value = LanDict[headerCellValue];
                        }
                        else
                        {
                            if (ChildrenChanged != null)
                            {
                                ChildrenAddedEventArgs args = new ChildrenAddedEventArgs();
                                args[headerCell] = headerCellValue;
                                ChildrenChanged(this, args);
                                LanDict[headerCellValue] = args[headerCell];
                                headerCell.Value = args[headerCell];
                                args = null;
                            }
                            else
                            {
                                string langText = LanguageHelper.GetLanguageText(headerCellValue);
                                LanDict[headerCellValue] = langText;
                                headerCell.Value = langText;
                            }
                        }
                    }
                }
            }
        }
        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public Dictionary<object, string> DefaultLangTexts
        {
            get
            {
                return cloumnHeaderTexts;
            }
        }
        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public Dictionary<object, string> CurrentLangTexts
        {
            get
            {
                try
                {
                    Dictionary<object, string> dict = new Dictionary<object, string>();
                    foreach (DataGridViewColumn item in this.Columns)
                    {
                        if (LanDict.ContainsKey(item.HeaderText))
                        {
                            dict.Add(item, LanDict[item.HeaderText]);
                        }
                    }
                    return dict;
                }
                catch (Exception)
                {
                    return null;
                }
            }
            set
            {
                if (System.Threading.Thread.CurrentThread.CurrentUICulture.Name != "zh-CHS")
                {
                    foreach (var item in value)
                    {
                        if (LanDict.ContainsKey(cloumnHeaderTexts[item.Key]))
                        {
                            LanDict[cloumnHeaderTexts[item.Key]] = item.Value;
                        }
                        else
                        {
                            LanDict.Add(cloumnHeaderTexts[item.Key], item.Value);
                        }

                        DataGridViewColumn dgvc = item.Key as DataGridViewColumn;
                        if (dgvc != null)
                        {
                            dgvc.HeaderText = item.Value;
                        }
                    }
                }
            }
        }

        public Control this[string ctrlName]
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        public void SetItemCurrentLangText(string ctrlName, string langText)
        {
            if (this.Columns[ctrlName] != null)
                this.Columns[ctrlName].HeaderText = langText;
        }

        protected override void OnColumnAdded(DataGridViewColumnEventArgs e)
        {
            base.OnColumnAdded(e);
            if (!string.IsNullOrWhiteSpace(e.Column.HeaderText))
            {
                if (LanDict.ContainsKey(e.Column.HeaderText))
                {
                    e.Column.HeaderText = LanDict[e.Column.HeaderText];
                }
                else
                {
                    cloumnHeaderTexts.Add(e.Column, e.Column.HeaderText);
                    if (ChildrenChanged != null)
                    {
                        ChildrenAddedEventArgs args = new ChildrenAddedEventArgs();
                        args[e.Column.HeaderCell] = e.Column.HeaderText;
                        ChildrenChanged(this, args);
                        LanDict[e.Column.HeaderText] = args[e.Column.HeaderCell];
                        e.Column.HeaderText = args[e.Column.HeaderCell];
                        args = null;
                    }
                    else
                    {
                        string langText = LanguageHelper.GetLanguageText(e.Column.HeaderText);
                        LanDict[e.Column.HeaderText] = langText;
                        e.Column.HeaderText = langText;
                    }
                }
            }
        }


        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public event EventHandler<ChildrenAddedEventArgs> ChildrenChanged;
    }

  

MyStyleMenuStrip:(MyStyleToolStrip、MyStyleStatusStrip實現程式碼均相同)

    public partial class MyStyleMenuStrip : MenuStrip, IMultiLanguageContainerControl
    {
        static Dictionary<string, string> LanDict = new Dictionary<string, string>();
        Dictionary<object, string> toolStripItemTexts = new Dictionary<object, string>();

        public MyStyleMenuStrip()
        {
            toolStripItemTexts.Clear();

            this.Renderer.RenderItemText += (s, e) =>
            {
                if (e.Item is ToolStripSeparator ||
                    e.Item is ToolStripComboBox ||
                    e.Item is ToolStripTextBox)
                {
                    return;

                }
                if (e.ToolStrip == this || GetItemTopToolStrip(e.Item) == this)
                {
                    e.Item.TextChanged += Item_TextChanged;
                    if (LanDict.ContainsValue(e.Item.Text))
                    {
                        return;
                    }
                    if (LanDict.ContainsKey(e.Item.Text))
                    {
                        e.Item.Text = LanDict[e.Item.Text];
                    }
                    else
                    {
                        SetItemLangText(e.Item);
                    }
                }
            };
        }
        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public Dictionary<object, string> DefaultLangTexts
        {
            get
            {
                foreach (ToolStripItem item in Items)
                {
                    GetItemText(item);
                }
                return toolStripItemTexts;
            }
        }
        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public Dictionary<object, string> CurrentLangTexts
        {
            get
            {
                try
                {
                    Dictionary<object, string> dict = new Dictionary<object, string>();
                    foreach (ToolStripItem item in this.Items)
                    {
                        if (LanDict.ContainsKey(item.Text))
                        {
                            dict.Add(item, LanDict[item.Text]);
                        }
                    }
                    return dict;
                }
                catch (Exception)
                {
                    return null;
                }
            }
            set
            {
                if (System.Threading.Thread.CurrentThread.CurrentUICulture.Name != "zh-CHS")
                {
                    foreach (var item in value)
                    {
                        if (LanDict.ContainsKey(toolStripItemTexts[item.Key]))
                        {
                            LanDict[toolStripItemTexts[item.Key]] = item.Value;
                        }
                        else
                        {
                            LanDict.Add(toolStripItemTexts[item.Key], item.Value);
                        }

                        ToolStripItem tsi = item.Key as ToolStripItem;
                        if (tsi != null)
                        {
                            tsi.Text = item.Value;
                        }
                    }
                }
            }
        }

        public Control this[string ctrlName]
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        public void SetItemCurrentLangText(string ctrlName, string langText)
        {
            if (this.Items[ctrlName] != null)
                this.Items[ctrlName].Text = langText;
        }
        protected override void OnItemAdded(ToolStripItemEventArgs e)
        {
            base.OnItemAdded(e);
            if (e.Item.Text.Length == 0 || e.Item.Text == "還原(&R)" || e.Item.Text == "最小化(&N)" || e.Item.Text == "關閉(&C)")
            {
                return;
            }
            if (e.Item is ToolStripSeparator ||
                e.Item is ToolStripComboBox ||
                e.Item is ToolStripTextBox)
            {
                return;
            }
            e.Item.TextChanged += Item_TextChanged;
            if (!string.IsNullOrWhiteSpace(e.Item.Text))
            {
                if (LanDict.ContainsKey(e.Item.Text))
                {
                    e.Item.Text = LanDict[e.Item.Text];
                }
                else
                {
                    toolStripItemTexts.Add(e.Item, e.Item.Text);
                }
            }
        }

        private void Item_TextChanged(object sender, EventArgs e)
        {
            ToolStripItem Item = sender as ToolStripItem;
            if (Item == null)
            {
                return;
            }
            if (string.IsNullOrWhiteSpace(Item.Text))
            {
                return;
            }
            if (LanDict.ContainsValue(Item.Text))
            {
                return;
            }
            if (LanDict.ContainsKey(Item.Text))
            {
                Item.Text = LanDict[Item.Text];
            }
            else
            {
                if (toolStripItemTexts.ContainsKey(Item))
                {
                    toolStripItemTexts[Item] = Item.Text;
                }
                else
                {
                    toolStripItemTexts.Add(Item, Item.Text);
                }
                SetItemLangText(Item);
            }
        }

        private void GetItemText(ToolStripItem item)
        {
            ToolStripMenuItem menuItem = item as ToolStripMenuItem;
            if (menuItem == null)
            {
                return;
            }
            foreach (ToolStripItem tsmi in menuItem.DropDownItems)
            {
                if (tsmi is ToolStripSeparator ||
                    tsmi is ToolStripComboBox ||
                    tsmi is ToolStripTextBox)
                {
                    continue;
                }
                tsmi.TextChanged += Item_TextChanged;
                if (!string.IsNullOrWhiteSpace(tsmi.Text))
                {
                    if (LanDict.ContainsKey(tsmi.Text))
                    {
                        tsmi.Text = LanDict[tsmi.Text];
                    }
                    else
                    {
                        toolStripItemTexts.Add(tsmi, tsmi.Text);
                    }
                }
                GetItemText(tsmi);
            }
        }

        private MyStyleMenuStrip GetItemTopToolStrip(ToolStripItem item)
        {
            if (item.OwnerItem == null)
            {
                return item.Owner as MyStyleMenuStrip;
            }
            else
            {
                return GetItemTopToolStrip(item.OwnerItem);
            }
        }

        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public event EventHandler<ChildrenAddedEventArgs> ChildrenChanged;

        private void SetItemLangText(ToolStripItem item)
        {
            if (ChildrenChanged != null)
            {
                ChildrenAddedEventArgs args = new ChildrenAddedEventArgs();
                args[item] = item.Text;
                ChildrenChanged(this, args);
                LanDict[item.Text] = args[item];
                item.Text = args[item];
                args = null;
            }
            else
            {
                string langText = LanguageHelper.GetLanguageText(item.Text);
                LanDict[item.Text] = langText;
                item.Text = langText;
            }
        }
    }

  

MyStyleTabControl:

    public partial class MyStyleTabControl : MyTabControl, IMultiLanguageContainerControl
    {
        static Dictionary<string, string> LanDict = new Dictionary<string, string>();
        Dictionary<object, string> tabPageTexts = new Dictionary<object, string>();

        public MyStyleTabControl()
        {
            tabPageTexts.Clear();
        }
        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public Dictionary<object, string> DefaultLangTexts
        {
            get
            {
                return tabPageTexts;
            }
        }
        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public Dictionary<object, string> CurrentLangTexts
        {
            get
            {
                try
                {
                    Dictionary<object, string> dict = new Dictionary<object, string>();
                    foreach (TabPage item in this.TabPages)
                    {
                        if (LanDict.ContainsKey(item.Text))
                        {
                            dict.Add(item, LanDict[item.Text]);
                        }
                    }
                    return dict;
                }
                catch (Exception)
                {
                    return null;
                }
            }
            set
            {
                if (System.Threading.Thread.CurrentThread.CurrentUICulture.Name != "zh-CHS")
                {
                    foreach (var item in value)
                    {
                        if (LanDict.ContainsKey(tabPageTexts[item.Key]))
                        {
                            LanDict[tabPageTexts[item.Key]] = item.Value;
                        }
                        else
                        {
                            LanDict.Add(tabPageTexts[item.Key], item.Value);
                        }

                        TabPage tp = item.Key as TabPage;
                        if (tp != null)
                        {
                            tp.Text = item.Value;
                        }
                    }
                }
            }
        }

        public Control this[string ctrlName]
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        public void SetItemCurrentLangText(string ctrlName, string langText)
        {
            if (this.TabPages[ctrlName] != null)
                this.TabPages[ctrlName].Text = langText;
        }

        protected override void OnControlAdded(ControlEventArgs e)
        {
            base.OnControlAdded(e);

            TabPage page = null;
            if ((page = e.Control as TabPage) != null)
            {
                page.TextChanged += page_TextChanged;
                if (!string.IsNullOrWhiteSpace(page.Text))
                {
                    if (LanDict.ContainsKey(page.Text))
                    {
                        page.Text = LanDict[page.Text];
                    }
                    else
                    {
                        tabPageTexts.Add(page, page.Text);
                    }
                }
            }
        }

        void page_TextChanged(object sender, EventArgs e)
        {
            TabPage page = sender as TabPage;
            if (page == null)
            {
                return;
            }
            if (string.IsNullOrWhiteSpace(page.Text))
            {
                return;
            }
            if (LanDict.ContainsValue(page.Text))
            {
                return;
            }
            if (LanDict.ContainsKey(page.Text))
            {
                page.Text = LanDict[page.Text];
            }
            else
            {
                if (tabPageTexts.ContainsKey(page))
                {
                    tabPageTexts[page] = page.Text;
                }
                else
                {
                    tabPageTexts.Add(page, page.Text);
                }
                if (ChildrenChanged != null)
                {
                    ChildrenAddedEventArgs args = new ChildrenAddedEventArgs();
                    args[page] = page.Text;
                    ChildrenChanged(this, args);
                    LanDict[page.Text] = args[page];
                    page.Text = args[page];
                    args = null;
                }
                else
                {
                    string langText = LanguageHelper.GetLanguageText(page.Text);
                    LanDict[page.Text] = langText;
                    page.Text = langText;
                }
            }
        }

        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public event EventHandler<ChildrenAddedEventArgs> ChildrenChanged;
    }

  

MyStyleTreeView:

    public partial class MyStyleTreeView : MyTreeView, IMultiLanguageContainerControl
    {
        static Dictionary<string, string> LanDict = new Dictionary<string, string>();
        Dictionary<object, string> nodeTexts = new Dictionary<object, string>();

        public MyStyleTreeView()
        {
            nodeTexts.Clear();
            this.DrawMode = TreeViewDrawMode.OwnerDrawText;
            this.AfterExpand += MyStyleTreeView_AfterExpand;
        }

        private void MyStyleTreeView_AfterExpand(object sender, TreeViewEventArgs e)
        {
            this.Refresh();
        }
        protected override void OnDrawNode(DrawTreeNodeEventArgs e)
        {
            IntPtr hdc = e.Graphics.GetHdc();
            Graphics g = Graphics.FromHdc(hdc);
            g.SmoothingMode = SmoothingMode.AntiAlias;
            Font nodeFont = e.Node.NodeFont;
            if (nodeFont == null) nodeFont = this.Font;
            Color foreColor = Color.Black;
            Color backColor = this.BackColor;
            if (this.ContainsFocus && (e.Node.IsSelected || (e.State & TreeNodeStates.Focused) != 0))
            {
                foreColor = Color.White;
                backColor = Color.FromArgb(51, 153, 255);
            }

            string txt = e.Node.Text;
            if (!string.IsNullOrWhiteSpace(txt) && !DesignMode)
            {
                if (LanDict.ContainsKey(e.Node.Text))
                {
                    txt = LanDict[e.Node.Text];
                }
                else
                {
                    if (ChildrenChanged != null)
                    {
                        ChildrenAddedEventArgs args = new ChildrenAddedEventArgs();
                        args[e.Node] = txt;
                        ChildrenChanged(this, args);
                        LanDict[txt] = args[e.Node];
                        txt = args[e.Node];
                        args = null;
                    }
                    else
                    {
                        string langText = LanguageHelper.GetLanguageText(txt);
                        LanDict[txt] = langText;
                        txt = langText;
                    }
                }
            }
            SizeF txtSize = g.MeasureString(txt, Font);
            Rectangle txtRect = new Rectangle(e.Bounds.X, e.Bounds.Y, (int)txtSize.Width + 2, e.Bounds.Height);
            using (SolidBrush sb = new SolidBrush(backColor))
            {
                g.FillRectangle(sb, txtRect);
            }
            TextRenderer.DrawText(
                    g,
                    txt,
                    Font,
                    txtRect,
                    foreColor,
                    TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter);

            e.Graphics.ReleaseHdc(hdc);
            g.Dispose();
        }


        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public Dictionary<object, string> DefaultLangTexts
        {
            get
            {
                nodeTexts.Clear();
                foreach (TreeNode item in this.Nodes)
                {
                    if (LanDict.ContainsKey(item.Text))
                    {
                        item.Text = LanDict[item.Text];
                    }
                    else
                    {
                        nodeTexts.Add(item, item.Text);
                    }
                    GetNodeText(item);
                }

                return nodeTexts;
            }
        }
        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public Dictionary<object, string> CurrentLangTexts
        {
            get
            {
                try
                {
                    Dictionary<object, string> dict = new Dictionary<object, string>();
                    Dictionary<object, string> defaultLangTexts = DefaultLangTexts;
                    foreach (var item in defaultLangTexts)
                    {
                        if (LanDict.ContainsKey(item.Value))
                        {
                            dict[item.Key] = LanDict[item.Value];
                        }
                        else
                        {
                            dict[item.Key] = "";
                        }
                    }
                    return dict;
                }
                catch (Exception)
                {
                    return null;
                }
            }
            set
            {
                if (System.Threading.Thread.CurrentThread.CurrentUICulture.Name != "zh-CHS")
                {
                    foreach (var item in value)
                    {
                        if (LanDict.ContainsKey(nodeTexts[item.Key]))
                        {
                            LanDict[nodeTexts[item.Key]] = item.Value;
                        }
                        else
                        {
                            LanDict.Add(nodeTexts[item.Key], item.Value);
                        }
                    }
                }
            }
        }

        public Control this[string ctrlName]
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        public void SetItemCurrentLangText(string ctrlName, string langText)
        {
            if (this.Nodes[ctrlName] != null)
                this.Nodes[ctrlName].Text = langText;
        }

        private void GetNodeText(TreeNode node)
        {
            if (node.Nodes.Count == 0)
            {
                return;
            }
            foreach (TreeNode tn in node.Nodes)
            {
                if (LanDict.ContainsKey(tn.Text))
                {
                    tn.Text = LanDict[tn.Text];
                }
                else
                {
                    nodeTexts.Add(tn, tn.Text);
                }
                GetNodeText(tn);
            }
        }
        [Browsable(false)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public event EventHandler<ChildrenAddedEventArgs> ChildrenChanged;

    }

 二次封裝這些控制元件的目的是:1.暴露統一的屬性,便於直接遍歷並賦值(僅當直接改變文字內容語言時需要);2.當文字內容或子控制元件文字內容或新增子控制元件發生改變時,能夠根據語言快取字典,快速直接的自我簡繁轉換,無需再次遍歷;

五.LanguageHelper:語方轉換公共類,與方案一原理相同,但相對方案一要簡單很多,程式碼如下:

public class LanguageHelper
    {
        #region 控制元件內容簡繁體轉換

        /// <summary>
        /// 設定控制元件的語言
        /// </summary>
        /// <param name="parent"></param>
        public static void SetControlLanguageText(System.Windows.Forms.Control ctrl)
        {
            if (ctrl.HasChildren)
            {
                foreach (Control item in ctrl.Controls)
                {
                    if (item is IMultiLanguageControl)
                    {
                        IMultiLanguageControl il = item as IMultiLanguageControl;
                        string value = GetLanguageText(il.DefaultLangText);
                        il.CurrentLangText = value;
                    }
                    if (item is IMultiLanguageContainerControl)
                    {
                        IMultiLanguageContainerControl lic = item as IMultiLanguageContainerControl;
                        Dictionary<object, string> dic = new Dictionary<object, string>();
                        foreach (var v in lic.DefaultLangTexts)
                        {
                            dic.Add(v.Key, GetLanguageText(v.Value));
                        }
                        lic.CurrentLangTexts = dic;
                        lic.ChildrenChanged += (s, e) =>
                        {
                            List<object> keyList = new List<object>();
                            foreach (var key in e.LangTexts.Keys)
                            {
                                keyList.Add(key);
                            }
                            keyList.ForEach(x =>
                            {
                                e[x] = GetLanguageText(e[x]);
                            });
                            keyList = null;
                        };
                    }

                    if (item.HasChildren)
                    {
                        SetControlLanguageText(item);
                    }
                }
            }
            else
            {
                IMultiLanguageControl il = ctrl as IMultiLanguageControl;
                string value = GetLanguageText(il.DefaultLangText);
                il.CurrentLangText = value;
            }

        }

        /// <summary>
        /// 根據語言識別符號得到轉換後的值
        /// </summary>
        /// <param name="languageFlag"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string GetLanguageText(string value)
        {

            string languageFlag = Thread.CurrentThread.CurrentUICulture.Name;

            if (value == null || value == string.Empty)
            {
                return value;
            }
            switch (languageFlag.ToUpper())
            {
                case "ZH-CHT":
                    {
                        return ToTraditional(value);
                    }
                default:
                    {
                        return ToSimplified(value);
                    }
            }
        }

        /// <summary> 
        /// 簡體轉換為繁體
        /// </summary> 
        /// <param name="str">簡體字</param> 
        /// <returns>繁體字</returns> 
        private static string ToTraditional(string str)
        {
            if (string.IsNullOrEmpty(str))
                return str;
            return ChineseConverter.Convert(str, ChineseConversionDirection.SimplifiedToTraditional);

        }
        /// <summary> 
        /// 繁體轉換為簡體
        /// </summary> 
        /// <param name="str">繁體字</param> 
        /// <returns>簡體字</returns> 
        private static string ToSimplified(string str)
        {
            if (string.IsNullOrEmpty(str))
                return str;
            return ChineseConverter.Convert(str, ChineseConversionDirection.TraditionalToSimplified);
        }
        #endregion

    }

Common.IsChsLanguage方法定義如下:

        public static bool IsChsLanguage()
        {
            return System.Threading.Thread.CurrentThread.CurrentUICulture.Name.Equals("zh-CHS", StringComparison.OrdinalIgnoreCase);
        }

  

多語言支援的容器類控制元件的實現難點是:捕獲子控制元件文字內容的改變,由於沒有現成的事件或方法,故需要通過其它的途徑來實現文字內容改時能夠進行處理。

以上就是本文的全部內容,有人可能會說,為何不採用資原始檔的形式,原因文章一開頭就說明了,是在原有的系統上,且不能改變原有的編碼風格,故才花了這麼大的力氣來實現這個簡繁轉換的功能,我公司經領導確認最終採用的方案二。文中若有不足,歡迎交流,謝謝!

注:控制元件的實現程式碼都貼出來了,大家若需要的話,可以直接COPY走,另外為了系統安全,簡繁體的系統截圖我就不貼出來了,大家可以自行測試。

相關文章