.NET Culture change event?

早过忘川 提交于 2019-12-18 05:09:26

问题


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?


回答1:


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.




回答2:


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...



来源:https://stackoverflow.com/questions/652505/net-culture-change-event

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!