当开发时某些软件具有特定的日期格式,需要设置系统日期格式,保证软件正常运行。
DllImport需要using System.Runtime.InteropServices;
[DllImport("kernel32.dll", EntryPoint = "SetLocaleInfoA")]
public static extern int SetLocaleInfo(int Locale, int LCType, string lpLCData);
[DllImport("user32.dll", EntryPoint = "SendMessageTimeout")]
public static extern long SendMessageTimeout(int hWnd, int Msg, int wParam, int lParam, int fuFlags, int uTimeout, ref int lpdwResult);
[DllImport("User32.dll", EntryPoint = "PostMessage")]
public static extern int PostMessage(
int hWnd, // handle to destination window
int Msg, // message
int wParam, // first message parameter
int lParam // second message parameter
);
public const int LOCALE_USER_DEFAULT = 0x0400;
public const int LOCALE_SYSTEM_DEFAULT = 0x0800;
public const int LOCALE_SSHORTDATE = 0x1F;
public const int LOCALE_STIMEFORMAT = 0x1003;
public const int HWND_BROADCAST = 0xFFFF;
public const int WM_SETTINGCHANGE = 0x001A;
public const int SMTO_ABORTIFHUNG = 2;
public static void SetDateTimeFormat()
{
int p = 0;
//设置短日期格式
SetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_SSHORTDATE, "yyyy-MM-dd");
//设置时间格式,24小时制
SetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_STIMEFORMAT, "HH:mm:ss");
//设置完成后必须调用,通知其他程序格式已经更改,否则即使是程序自身也不能使用新设置的格式
SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0, 0, SMTO_ABORTIFHUNG, 10,ref p);
}