简体   繁体   English

如何获取C#中的控制面板货币格式

[英]How to obtain the control panel currency format in C#

Our report generator works fine when the culture setting uses "$" for currency symbol. 当区域性设置使用“ $”作为货币符号时,我们的报告生成器可以正常工作。

Now we want to use this in European and use "€" instead. 现在我们要在欧洲使用它,而使用“€”。

I went to control panel, change the "Region and Language" format to "Danish (Denmark)" and apply the change. 我转到控制面板,将“地区和语言”格式更改为“丹麦语(丹麦)”并应用更改。

Now open Excel and type in a number then set the cell format to currency, the currency symbol is updated. 现在打开Excel并输入数字,然后将单元格格式设置为货币,货币符号将更新。

However, our report generator is still using "$". 但是,我们的报告生成器仍在使用“ $”。 When debugging the software we found that CultureInfo.CurrentCulture is still a culture using "$" (ie, en-AU ). 在调试软件时,我们发现CultureInfo.CurrentCulture仍然是使用“ $”(即en-AU )的区域性。

(The code is trivial but I just simply written down here:) (代码很简单,但我只是在这里写下:)

result = ValueToDisplay.ToString("C"); //CultureInfo.CurrentCulture is "en-AU"

I recon this might not be a real problem when the user's computer is in European since in that case CultureInfo.CurrentCulture will be different. 我认为当用户的计算机使用欧洲语言时,这可能不是一个真正的问题,因为在这种情况下, CultureInfo.CurrentCulture将有所不同。

However, obviously Excel can correspond to the setting change in control panel without even reboot the computer, so in theory our software should be able to do so as well. 但是,显然Excel甚至可以在不重新启动计算机的情况下对应于控制面板中的设置更改,因此,从理论上讲,我们的软件也应该能够这样做。

So how do we work like Excel? 那么我们如何像Excel一样工作呢?

Thanks to the hints, I found that our program do reset the culture and stored the original culture somewhere else. 多亏了这些提示,我发现我们的程序确实重置了区域性并将原始区域性存储在其他位置。 When change the code to 将代码更改为

result = ValueToDisplay.ToString("C", originalCulture);

this works fine. 这很好。

You can handle this without a restart of your application by listening for the event that indicates the locale has changed and then clearing the CultureInfo cache. 您可以通过侦听指示语言环境已更改的事件,然后清除CultureInfo缓存来处理此问题而无需重新启动应用程序。

To listen for the event, you can do this: 要收听事件,您可以执行以下操作:

SystemEvents.UserPreferenceChanged += SystemEvents_UserPreferenceChanged;

Then in the event handler, you can clear the Culture cache: 然后,在事件处理程序中,您可以清除区域性缓存:

private void SystemEvents_UserPreferenceChanged(object sender, UserPreferenceChangedEventArgs e)
{
    if (e.Category == UserPreferenceCategory.Locale)
        CultureInfo.CurrentCulture.ClearCachedData();
}

Now, when you run code like this: 现在,当您运行如下代码时:

var number = 21.00;
MessageBox.Show(number.ToString("C"));

You will get the correct output based on whatever locale information the user has changed. 您将根据用户更改的任何区域设置信息获得正确的输出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM