How do I change the culture of a WinForms application at runtime

后端 未结 3 674
攒了一身酷
攒了一身酷 2020-11-29 10:19

I have created Windows Form Program in C#. I have some problems with localization. I have resource files in 2 languages(one is for english and another is for french). I want

3条回答
  •  自闭症患者
    2020-11-29 11:06

    Updating the CultureInfo at runtime might reset component size. This code preserves the size and position of the controls (there will still be visible flickering though, which using SuspendLayout() couldn't fix)

    
        private void langItem_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            //I store the language codes in the Tag field of list items
            var itemClicked = e.ClickedItem;
            string culture = itemClicked.Tag.ToString().ToLower();
    
            Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(culture);
            ApplyResourceToControl(
            this,
            new ComponentResourceManager(typeof(GUI)),
            new CultureInfo(culture));           
        }
    
        private void ApplyResourceToControl(
           Control control,
           ComponentResourceManager cmp,
           CultureInfo cultureInfo)
        {
            foreach (Control child in control.Controls)
            {
                //Store current position and size of the control
                var childSize = child.Size;
                var childLoc = child.Location;
                //Apply CultureInfo to child control
                ApplyResourceToControl(child, cmp, cultureInfo);
                //Restore position and size
                child.Location = childLoc;
                child.Size = childSize;
            }
            //Do the same with the parent control
            var parentSize = control.Size;
            var parentLoc = control.Location;
            cmp.ApplyResources(control, control.Name, cultureInfo);
            control.Location = parentLoc;
            control.Size = parentSize;
        }
    

提交回复
热议问题