I have created Windows Form Program in C#.
I have some problems with localization.
I have resource files in 3 languages.
I want to click each language button and change language at runtime.
When i am changing language before InitializeComponent()
it works.
But when i am clicking on button, it doesn't work.
i am using this code.
private void RussianFlag_Click(object sender, EventArgs e)
{
Thread.CurrentThread.CurrentUICulture = new CultureInfo("ru-RU");
}
I wrote a RuntimeLocalizer
class with following features:
Control
s and SubControl
s in a FormSubItem
s of all MenuStrip
sUsage Example: RuntimeLocalizer.ChangeCulture(MainForm, "en-US");
using System.Windows.Forms;
using System.Globalization;
using System.Threading;
using System.ComponentModel;
public static class RuntimeLocalizer
{
public static void ChangeCulture(Form frm, string cultureCode)
{
CultureInfo culture = CultureInfo.GetCultureInfo(cultureCode);
Thread.CurrentThread.CurrentUICulture = culture;
ComponentResourceManager resources = new ComponentResourceManager(frm.GetType());
ApplyResourceToControl(resources, frm, culture);
resources.ApplyResources(frm, "$this", culture);
}
private static void ApplyResourceToControl(ComponentResourceManager res, Control control, CultureInfo lang)
{
if (control.GetType() == typeof(MenuStrip)) // See if this is a menuStrip
{
MenuStrip strip = (MenuStrip)control;
ApplyResourceToToolStripItemCollection(strip.Items, res, lang);
}
foreach (Control c in control.Controls) // Apply to all sub-controls
{
ApplyResourceToControl(res, c, lang);
res.ApplyResources(c, c.Name, lang);
}
// Apply to self
res.ApplyResources(control, control.Name, lang);
}
private static void ApplyResourceToToolStripItemCollection(ToolStripItemCollection col, ComponentResourceManager res, CultureInfo lang)
{
for (int i = 0; i < col.Count; i++) // Apply to all sub items
{
ToolStripItem item = (ToolStripMenuItem)col[i];
if (item.GetType() == typeof(ToolStripMenuItem))
{
ToolStripMenuItem menuitem = (ToolStripMenuItem)item;
ApplyResourceToToolStripItemCollection(menuitem.DropDownItems, res, lang);
}
res.ApplyResources(item, item.Name, lang);
}
}
}
You will need to reload the controls for it to reflect the New culture values
ComponentResourceManager resources = new ComponentResourceManager(typeof(Form1));
and then you would have to apply for each control using resources.ApplyResources
Please have a look here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With