Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Culture change event?

Tags:

.net

culture

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?

like image 668
Phil Wright Avatar asked Mar 16 '09 23:03

Phil Wright


1 Answers

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.

like image 172
Groo Avatar answered Oct 12 '22 22:10

Groo