Change program locale at runtime in C#

[Change program locale at runtime][Change program locale at runtime]

This example lets you change program locale at runtime so you can test localized programs.

The example Test localized programs in C# explains how you can make a program select a specific locale when it starts so you can test different locales. This example shows how you can make that change at runtime.

The SetCulture method shown below selects a specific culture.

// Set the form's culture.
private void SetCulture(string culture)
{
    // Make the CultureInfo.
    CultureInfo culture_info = new CultureInfo(culture);

    // Make a ComponentResourceManager.
    ComponentResourceManager component_resource_manager
        = new ComponentResourceManager(this.GetType());

    // Apply resources to the form.
    component_resource_manager.ApplyResources(
        this, "$this", culture_info);

    // Apply resources to the form's controls.
    foreach (Control ctl in this.Controls)
    {
        component_resource_manager.ApplyResources(
            ctl, ctl.Name, culture_info);
    }
}

The code makes a new CultureInfo object to represent the desired culture. It then makes a ComponentResourceManager for the culture and uses its ApplyResources method to load the culture-specific resources for the form and its controls.

The following code shows how the example loads its resources for English or German when you select the corresponding radio button.

private void radEnglish_Click(object sender, EventArgs e)
{
    SetCulture("en-US");
}

private void radGerman_Click(object sender, EventArgs e)
{
    SetCulture("de-DE");
}

This example actually isn’t localized for English but that’s what I used when making the default localization so that’s what you get if you select en-EN or any other culture for which it isn’t localized. For example, try fr-FR or es-MX.


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in globalization, internationalization, localization and tagged , , , , , , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *