C#实现多语言切换

代码:https://github.com/tangbb1/C-shop/tree/master
思路描述:
①窗体的language属性修改为自己需要设定语言 localizable属性改为true。在窗体上进行英文编辑,即可生成对应的资源文件在这里插入图片描述
在这里插入图片描述
②根据组件名称读取资源文件内容
在这里插入图片描述
③其中除窗口对应的字段之外,还有类似MessageBox的固定字段,及代码中默认设定值。须在资源文件中自定义该类字段
在这里插入图片描述
使用代码读取:
public static ResourceManager res = new ResourceManager(typeof(nonUIresx)); //自定义资源字段
res.GetString(“saveFault”)

在这里插入图片描述
注:主要代码如下:(设置默认语言;遍历组件;重写messagebox;

using DevExpress.XtraBars;
using DevExpress.XtraBars.Ribbon;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace BingSolhalcon
{
     class MultiLanguage
    {
        //当前默认语言
        public static string DefaultLanguage = "zh";


        /// <summary>
        /// 修改默认语言
        /// </summary>
        /// <param name="lang">待设置默认语言</param>
        public  void SetDefaultLanguage(string lang)
        {
            System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(lang);
            DefaultLanguage = lang;
            Properties.Settings.Default.DefaultLanguage = lang;
            Properties.Settings.Default.Save();
        }

        public void LoadDefaultLanguage(Form form, Type formType)
        {
            string language = Properties.Settings.Default.DefaultLanguage;
            System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(language);
            MultiLanguage multiLanguage = new MultiLanguage();
            //加载默认语言
            multiLanguage.LoadLanguage(form, formType);
        }

        /// <summary>
        /// 加载语言
        /// </summary>
        /// <param name="form">加载语言的窗口</param>
        /// <param name="formType">窗口的类型</param>
        public  void LoadLanguage(Form form, Type formType)
        {
            if (form != null)
            {
                System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(formType);
                resources.ApplyResources(form, "$this");
                Loading(form, resources);
            }
        }

        /// <summary>
        /// 加载语言
        /// </summary>
        /// <param name="control">控件</param>
        /// <param name="resources">语言资源</param>
        private static void Loading(Control control, System.ComponentModel.ComponentResourceManager resources)
        {
            if (control is RibbonControl)
            {
                //将资源与控件对应
                resources.ApplyResources(control, control.Name);
                RibbonControl ms = (RibbonControl)control;
                if (ms.Pages.Count > 0)
                {
                    foreach (RibbonPage c in ms.Pages)
                    {
                        resources.ApplyResources(c, c.Name);
                    }
                }
                if (ms.Items.Count > 0)
                {
                    foreach (BarItem c in ms.Items)
                    {
                        //将资源与控件对应
                        Loading(c, resources);
                    }
                }
            }

            if (control is ComboBox)
            {
                //将资源与控件对应
                //登陆界面中的combox暂时处理
                resources.ApplyResources(control, control.Name);
                ComboBox cb = (ComboBox)control;
                if (cb.FindForm().Name == "LogIn")
                {
                    cb.Items.Clear();
                    cb.Items.Add("Operator");
                    cb.Items.Add("Technician");
                    cb.Items.Add("Expert");
                }  
            }


            foreach (Control c in control.Controls)
            {
                resources.ApplyResources(c, c.Name);
                Loading(c, resources);
            }
        }

        private static void Loading(BarItem control, System.ComponentModel.ComponentResourceManager resources)
        {
            resources.ApplyResources(control, control.Name);
        }

    }

    class MessageBoxEX
    {
        public static DialogResult Show(string text, string caption, MessageBoxButtons buttons, string[] buttonTitles)
        {
            MessageForm frm = new MessageForm(buttons, buttonTitles);
            frm.Show();
            frm.WatchForActivate = true;
            DialogResult result = MessageBox.Show(frm, text, caption, buttons);
            frm.Close();
            return result;
        }

        public static DialogResult Show(string text, string caption, MessageBoxButtons buttons,
            MessageBoxIcon icon, MessageBoxDefaultButton defaultButton, string[] buttonTitles)
        {
            MessageForm frm = new MessageForm(buttons, buttonTitles);
            frm.Show();
            frm.WatchForActivate = true;
            DialogResult result = MessageBox.Show(frm, text, caption, buttons, icon, defaultButton);
            frm.Close();
            return result;
        }

        class MessageForm : Form
        {
            IntPtr _handle;
            MessageBoxButtons _buttons;
            string[] _buttonTitles = null;

            bool _watchForActivate = false;

            public bool WatchForActivate
            {
                get { return _watchForActivate; }
                set { _watchForActivate = value; }
            }

            public MessageForm(MessageBoxButtons buttons, string[] buttonTitles)
            {
                _buttons = buttons;
                _buttonTitles = buttonTitles;

                // Hide self form, and don't show self form in task bar.
                this.Text = "";
                this.StartPosition = FormStartPosition.CenterScreen;
                this.Location = new Point(-32000, -32000);
                this.ShowInTaskbar = false;
                this.TopMost = true;
            }

            protected override void OnShown(EventArgs e)
            {
                base.OnShown(e);
                // Hide self form, don't show self form even in task list.
                NativeWin32API.SetWindowPos(this.Handle, IntPtr.Zero, 0, 0, 0, 0, 659);
            }

            protected override void WndProc(ref System.Windows.Forms.Message m)
            {
                if (_watchForActivate && m.Msg == 0x0006)
                {
                    _watchForActivate = false;
                    _handle = m.LParam;
                    CheckMsgbox();
                }
                base.WndProc(ref m);
            }

            private void CheckMsgbox()
            {
                if (_buttonTitles == null || _buttonTitles.Length == 0)
                    return;

                // Button title index
                int buttonTitleIndex = 0;
                // Get the handle of control in current window.
                IntPtr h = NativeWin32API.GetWindow(_handle, GW_CHILD);

                // Set those custom titles to the three buttons(Default title are: Yes, No and Cancle).
                while (h != IntPtr.Zero)
                {
                    if (NativeWin32API.GetWindowClassName(h).Equals("Button"))
                    {
                        if (_buttonTitles.Length > buttonTitleIndex)
                        {
                            // Changes the text of the specified window's title bar (if it has one). 
                            // If the specified window is a control, the text of the control is changed. 
                            // However, SetWindowText cannot change the text of a control in another application.
                            NativeWin32API.SetWindowText(h, _buttonTitles[buttonTitleIndex]);

                            buttonTitleIndex++;
                        }
                    }

                    // Get the handle of next control in current window.
                    h = NativeWin32API.GetWindow(h, GW_HWNDNEXT);
                }
            }
        }


        public const int GW_CHILD = 5;
        public const int GW_HWNDNEXT = 2;

        public class NativeWin32API
        {
            [DllImport("user32.dll", CharSet = CharSet.Auto)]
            public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int Width, int Height, int flags);
            [DllImport("user32.dll")]
            public static extern IntPtr GetWindow(IntPtr hWnd, Int32 wCmd);
            [DllImport("user32.dll")]
            public static extern bool SetWindowText(IntPtr hWnd, string lpString);
            [DllImport("user32.dll")]
            public static extern int GetClassNameW(IntPtr hWnd, [MarshalAs(UnmanagedType.LPWStr)]StringBuilder lpString, int nMaxCount);

            public static string GetWindowClassName(IntPtr handle)
            {
                StringBuilder sb = new StringBuilder(256);

                // Retrieves the name of the class to which the specified window belongs
                GetClassNameW(handle, sb, sb.Capacity);
                return sb.ToString();
            }
        }

    }

}

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值