Visual Studio .NET 2002Visual Studio .NET 2003.NET 1.1Visual Studio 2005.NET 2.0C# 2.0中级开发Visual StudioWindows.NETC#
自定义全局应用程序区域设置






4.71/5 (9投票s)
本文档帮助您在应用程序启动时定义特定于应用程序的文化。
引言
很多时候,开发人员编写应用程序时会忘记不同的系统可能有不同的日期和时间格式设置。这会导致应用程序崩溃。本文档帮助您设置特定于应用程序的自定义全局文化信息环境。
背景
我正在处理一个现有的应用程序,并发现了开发人员的疏忽。如果我更改了系统设置,我就无法运行此应用程序 - 这个问题被分配给我修复。所以我这样做了。
Using the Code
代码不言自明。现在开发人员无需担心日期和时间格式的环境设置了。
在应用程序启动时设置并初始化所有文化设置
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
// Creating a Global culture specific to our application.
System.Globalization.CultureInfo cultureInfo =
new System.Globalization.CultureInfo("en-US");
// Creating the DateTime Information specific to our application.
System.Globalization.DateTimeFormatInfo dateTimeInfo =
new System.Globalization.DateTimeFormatInfo();
// Defining various date and time formats.
dateTimeInfo.DateSeparator = "/";
dateTimeInfo.LongDatePattern = "dd-MMM-yyyy";
dateTimeInfo.ShortDatePattern = "dd-MMM-yy";
dateTimeInfo.LongTimePattern = "hh:mm:ss tt";
dateTimeInfo.ShortTimePattern = "hh:mm tt";
// Setting application wide date time format.
cultureInfo.DateTimeFormat = dateTimeInfo;
// Assigning our custom Culture to the application.
Application.CurrentCulture = cultureInfo;
Thread.CurrentThread.CurrentCulture = cultureInfo;
Thread.CurrentThread.CurrentUICulture = cultureInfo;
..................
Application.Run(new Form1());
}
关注点
大多数人可能都尝试过同样的方法,但可能无法直接更改 DateFormat
。我尝试过多次更改 CurrentCulture.DateFormatInfo
,但是... :)
历史
- 2007年7月26日:初始发布