Localisation and accessibility

Two audiences a desktop form has to serve are easy to forget, because neither is the developer. One reads the window in another language, and one does not see the window at all. WinForms has a mechanism for each: satellite resource assemblies for the first, the accessibility properties of every control for the second. They meet in the same place, because a translated layout and an accessible one both depend on text that fits and labels that say what they mean.

Culture and the resources

Two culture properties matter, and they are not the same. CurrentCulture decides how numbers, dates and currency are parsed and formatted. CurrentUICulture decides which resource file the resource manager loads. A program can show dollars with an English interface in Germany, so the two are separate on purpose.

A form localised in the designer has one Form1.resx with the neutral strings and one Form1.de.resx with the German ones. At build time the second becomes a satellite assembly in a de folder next to the program, and the resource manager picks it when the UI culture is German. The lookup walks from the most specific culture to the neutral one: de-DE falls back to de, which falls back to the neutral file.

The culture has to be chosen before the first form is constructed, because the designer-generated InitializeComponent reads the resources as it runs. Main is the place:

using System; using System.Drawing; using System.Globalization; using System.Threading; using System.Windows.Forms; internal static class Program { [STAThread] private static void Main() { // Chosen before the first control exists: the resource manager and the // designer strings read CurrentUICulture when the form is created. Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("de"); ApplicationConfiguration.Initialize(); Application.Run(new SignInForm()); } } internal sealed class SignInForm : Form { public SignInForm() { Text = "Sign in"; ClientSize = new Size(400, 160); AccessibleName = "Sign-in window"; AccessibleRole = AccessibleRole.Dialog; var user = new TextBox { Location = new Point(120, 18), Width = 220, AccessibleName = "User name", AccessibleDescription = "Type the name you sign in with", }; var signIn = new Button { Text = "&Sign in", Location = new Point(120, 54), Size = new Size(100, 27), AccessibleRole = AccessibleRole.PushButton, AccessibleDefaultActionDescription = "Signs in with the name above", }; var hint = new Label { Text = "Press Alt+S to sign in", Location = new Point(16, 108), AutoSize = true, UseMnemonic = true, }; Controls.Add(new Label { Text = "&User name:", AutoSize = true, Location = new Point(16, 22) }); Controls.Add(user); Controls.Add(signIn); Controls.Add(hint); AcceptButton = signIn; } }

dotnet build app.csproj

Build succeeded.
    0 Warning(s)
    0 Error(s)

The listing is built and not run. The culture is set to German, but the strings are English, because this form has no SignInForm.de.resx: the resource manager finds no satellite and falls back to the neutral text. That is the behaviour to rely on when a translation is incomplete, and it is why a missing translation is a cosmetic problem rather than an exception.

The call to ApplicationConfiguration.Initialize() comes after the culture. It sets the default font and the high-DPI mode from the project file and reads no resource itself; what matters is that the culture is set before the form is constructed, and this is the last point where that is certain.

What a translated resx holds

The translated file is not a copy of the whole form. It holds the entries whose value differs, and the designer writes one per localised property, which by default is Text:

<?xml version="1.0" encoding="utf-8"?> <root> <resheader name="resmimetype"> <value>text/microsoft-resx</value> </resheader> <data name="signIn.Text" xml:space="preserve"> <value>Anmelden</value> </data> <data name="hint.Text" xml:space="preserve"> <value>Alt+S drücken, um sich anzumelden</value> </data> </root>

The name is the field name the designer gave the control plus the property, the same naming lesson 006 read in InitializeComponent. The access key survives translation only if the translator puts the ampersand on a character that exists in the word: &amp;Anmelden is Alt+A. A translation without an ampersand removes the keyboard route, which is a bug an accessibility review finds quickly.

Three practical rules. Keep the neutral file English and treat it as the source of keys. Do not put user data in a resource, because resources are compiled into the assembly. And translate the accessible names and descriptions as carefully as the visible text: a screen reader reads AccessibleName when it is set and the control's Text when it is not, so a German form with an English accessible name is half translated.

Accessibility properties

The accessibility tree is not a WinForms idea: Windows builds it through UI Automation, and the properties above are the parts WinForms exposes. A custom control that draws its own text has to expose its name and role explicitly, which is the subject of lesson 065.

A translator that runs

A form can also keep its strings in JSON and translate them itself, which is what an application with a plugin folder or a downloaded language pack does. The translator below reads two tables, falls back to English, marks a missing key and uses the invariant culture for the format arguments. It was built and run here:

using System; using System.Collections.Generic; using System.Globalization; using System.Text.Json; Console.WriteLine("a translator from two JSON tables"); var json = """ { "en": { "welcome": "Welcome, {0}!", "items": "{0} items" }, "de": { "welcome": "Willkommen, {0}!" } } """; var table = JsonSerializer.Deserialize<Dictionary<string, Dictionary<string, string>>>(json)!; var translator = new Translator(table, "en"); Console.WriteLine($"current UI culture: '{CultureInfo.CurrentUICulture.Name}'"); Console.WriteLine(translator.TranslateFor("welcome", "en", "Ada")); Console.WriteLine(translator.TranslateFor("welcome", "de", "Ada")); Console.WriteLine(translator.TranslateFor("items", "de", 3)); Console.WriteLine(translator.TranslateFor("missing", "de")); Console.WriteLine(translator.TranslateFor("items", "fr", 3)); CultureInfo.CurrentUICulture = new CultureInfo("de"); Console.WriteLine($"current UI culture: '{CultureInfo.CurrentUICulture.Name}'"); Console.WriteLine(translator.Translate("welcome", "Ada")); internal sealed class Translator { private readonly Dictionary<string, Dictionary<string, string>> _table; private readonly string _fallback; public Translator(Dictionary<string, Dictionary<string, string>> table, string fallback) { _table = table; _fallback = fallback; } public string Translate(string key, params object[] args) => TranslateFor(key, CultureInfo.CurrentUICulture.TwoLetterISOLanguageName, args); public string TranslateFor(string key, string culture, params object[] args) { var text = Find(culture, key) ?? Find(_fallback, key); if (text is null) { return $"[missing: {key}]"; } return string.Format(CultureInfo.InvariantCulture, text, args); } private string? Find(string culture, string key) => _table.TryGetValue(culture, out var strings) && strings.TryGetValue(key, out var text) ? text : null; }

dotnet run

a translator from two JSON tables
current UI culture: ''
Welcome, Ada!
Willkommen, Ada!
3 items
[missing: missing]
3 items
current UI culture: 'de'
Willkommen, Ada!

The output is the real run. The first culture line is empty because the container starts with the invariant culture, which has no name; a real desktop starts with the user's culture. The fourth call asked for a key that German does not have and got the English text, which is the fallback working. The fifth asked for a key no table has and got the marker, which is better than an empty label in a shipped form. The last call used the current culture after it was set, and the interface switched without a restart of the translator.

string.Format(InvariantCulture, …) formats the arguments, not the translated text. A number in a sentence should follow the user's culture, so a real translator passes CurrentCulture here; the invariant is used in this listing to keep the output identical on every machine, which is the same reason the course prints numbers the way it does.

Exercises

  1. Add a ru table to the JSON and a key that only Russian has; run the program and explain which fallback each call takes.
  2. Set CurrentCulture as well as CurrentUICulture and print a date with both, and explain the difference.
  3. Add AccessibleName to every control of the form and list which ones would be announced wrongly without it.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Which property decides which resource file is loaded?

    Answer

    CurrentUICulture

    CurrentCulture decides number and date formatting instead.

  2. Where does a de-DE UI culture look for strings first?

    Answer

    The de-DE satellite, then de, then the neutral file

    The lookup walks from the most specific culture to the neutral one.

  3. When must the culture be set?

    Answer

    Before the first form is constructed

    InitializeComponent reads the resources as it runs.

  4. What does a missing satellite assembly cause?

    Answer

    The neutral strings are used

    This form is in exactly that state: German culture, English strings.

  5. Which property does a screen reader announce for a text box?

    Answer

    AccessibleName when it is set, otherwise the control text

    Name is the field name used in code and has nothing to do with speech.

  6. What does AccessibleRole describe?

    Answer

    What the control is, such as Dialog or PushButton

    The default action description covers what it does.

  7. What did the translator print for a key German does not have?

    Answer

    The English text

    It falls back to the en table before giving up.

  8. What did it print for a key no table has?

    Answer

    The [missing: key] marker

    A visible marker is better than a silent empty label.

  9. Why is InvariantCulture used for string.Format in the listing?

    Answer

    To keep the output identical on every machine

    A real translator passes CurrentCulture; the lesson pins it for the run.

  10. What happens to an access key in a translated string without an ampersand?

    Answer

    The keyboard route is lost

    The translator has to put the ampersand on a character of the translated word.

Every listing on this page was built with the .NET SDK 10.0.303 for net10.0-windows against the targeting pack Microsoft.WindowsDesktop.App.Ref 10.0.15 from the offline feed, in a Docker container on Alpine Linux 3.24.3 (x86_64). The programs were built, not run on Linux: WinForms needs Windows. The logic that draws nothing was also run headless on the same machine, and its output is the run output printed below each of those programs.

Article author: Arthur Isaev

Banner image