views:

97

answers:

1

I want to detect the regional settings changes and show the dates in the correct format in a WPF application. But there is a strange problem with CultureInfo.ClearCachedData. It randomly either works either not. Does anybody know why, and a workaround for this ? I know that the regional settings are stored in the registry, but it's too primitive to decipher the content of HKCU\Control Panel\International and build a CultureInfo manually from it.

I've put this in a bigger application and the rate of CultureInfo.ClearCachedData failure is almost 100% there.

Window1.xaml.cs:

using System;
using System.Globalization;
using System.Windows;
using System.Windows.Interop;

namespace WpfApplication1
{
    partial class Window1 : Window
    {
        int i = 0;

        public Window1()
        {
            InitializeComponent();
            ShownCurrentCulture();
            Loaded += (x, y) => HwndSource.FromHwnd(
                new WindowInteropHelper(this).Handle).AddHook(WndProc);
        }

        IntPtr WndProc(IntPtr hwnd, int msg,
            IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            if (msg == 0x1a) // WM_SETTINGCHANGE
            {
                // CultureInfo.CurrentCulture is sometimes changed,
                // sometimes not
                ShownCurrentCulture();
            }
            return IntPtr.Zero;
        }

        void ShownCurrentCulture()
        {
            CultureInfo.CurrentCulture.ClearCachedData();
            Title = i++ + " " + CultureInfo.CurrentCulture;
        }
    }
}
A: 

After some more trials I found out that only the newly created threads get the updated culture correctly. CultureInfo.CurrentCulture on an old thread returns randomly either the old (Thread.CurrentThread.CurrentCulture) or the updated culture.

Probably if Thread.CurrentThread.CurrentCulture was modified, CultureInfo.CurrentCulture won't get updated on that tread after a call to ClearCachedData, otherwise it gets updated.

csuporj