How to change language at runtime without layout troubles

后端 未结 2 1650
旧巷少年郎
旧巷少年郎 2021-02-20 09:35

I have a winforms application that the users must be able to change the language at runtime.

To generalize the switch and avoid having to hard code control names I tried

2条回答
  •  离开以前
    2021-02-20 10:17

    This is the complete code I am using now.

    The change is to manually change the Text property only. If I get to localize other properties, the code will have to be expanded afterwards.

        /// 
        /// Change language at runtime in the specified form
        /// 
        internal static void SetLanguage(this Form form, CultureInfo lang)
        {
            //Set the language in the application
            System.Threading.Thread.CurrentThread.CurrentUICulture = lang;
    
            ComponentResourceManager resources = new ComponentResourceManager(form.GetType());
    
            ApplyResourceToControl(resources, form.MainMenuStrip, lang);
            ApplyResourceToControl(resources, form, lang);
    
            //resources.ApplyResources(form, "$this", lang);
            form.Text = resources.GetString("$this.Text", lang);
        }
    
        private static void ApplyResourceToControl(ComponentResourceManager resources, Control control, CultureInfo lang)
        {
            foreach (Control c in control.Controls)
            {
                ApplyResourceToControl(resources, c, lang);
                //resources.ApplyResources(c, c.Name, lang);
                string text = resources.GetString(c.Name+".Text", lang);
                if (text != null)
                    c.Text = text;
            }
        }
    
        private static void ApplyResourceToControl(ComponentResourceManager resources, MenuStrip menu, CultureInfo lang)
        {
            foreach (ToolStripItem m in menu.Items)
            {
                //resources.ApplyResources(m, m.Name, lang);
                string text = resources.GetString(m.Name + ".Text", lang);
                if (text != null)
                    m.Text = text;
            }
        }
    

提交回复
热议问题