Question

I have a .NET custom control that displays information in a culture dependant way. To improve performance I cache some information inside the control rather than generate it every time. I need to know if the culture has changed so that I can regenerate this internal info as appropriate.

Is there some event I have hook into? Or do I have to just test the culture setting every time I paint to see if it has changed?

Was it helpful?

Solution

You can either handle the SystemEvents.UserPreferenceChanged event:

SystemEvents.UserPreferenceChanged += (sender, e) => 
{
    // Regional settings have changed
    if (e.Category == UserPreferenceCategory.Locale)
    {
        // .NET also caches culture settings, so clear them
        CultureInfo.CurrentCulture.ClearCachedData();

        // do some other stuff
    }
};

Windows also broadcasts the WM_SETTINGSCHANGE message to all Forms. You could try detecting it by overriding WndProc, so it would look something like:

// inside a winforms Form
protected override void WndProc(ref Message m)
{
    const int WM_SETTINGCHANGE = 0x001A;

    if (m.Msg == WM_SETTINGCHANGE)
    {
        // .NET also caches culture settings, so clear them
        CultureInfo.CurrentCulture.ClearCachedData();

        // do some other stuff
    }

    base.WndProc(ref m);
}

Note that you probably also want to call CultureInfo.CurrentCulture.ClearCachedData() to invalidate the culture info for newly created threads, but keep in mind that CurrentCulture for existing threads won't be updated, as mentioned on MSDN:

The ClearCachedData method does not refresh the information in the Thread.CurrentCulture property for existing threads. However, future threads will have new CultureInfo property values.

OTHER TIPS

I suspect you could do this by having your code change the culture via a central property that itself does something like raise an event; but be very very careful: static events are a very easy way to keep an insane amount of objects stuck in memory (i.e. GC treats them as alive). If you go for this approach, you might want to look at things like WeakReference...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top