SetLocalInfo修改系统时间,立即生效

SetLocalInfo修改系统时间后,必须重启机器才能生效。为了能够立即生效,需要广播一次消息,

使用SetLocaleInfo()函数设置完后,要使用PostMessage()函数(此API在USER32.dll中)向系统广播该消息:WM_SETTINGCHANGE,这样才能让系统重新读取注册表信息并更新!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
using System.Runtime.InteropServices;
using Microsoft.Win32;
 
 
namespace ConsoleApplication1
{
    class Program
    {
 
        [DllImport("kernel32.dll", EntryPoint = "GetSystemDefaultLCID")]
        public static extern int GetSystemDefaultLCID();
 
        [DllImport("kernel32.dll", EntryPoint = "SetLocaleInfoA")]
        public static extern int SetLocaleInfo(int Locale, int LCType, string lpLCData);
 
        [DllImport("user32.dll", EntryPoint = "SendMessage")]
        public static extern int SendMessage(int hwnd, int wMsg, int wParam, int lParam);
 
        const int WM_SETTINGCHANGE = 0x001A;
        const int HWND_BROADCAST = 0xffff;
        public const int LOCALE_SSHORTDATE = 0x1F;
 
        static void Main(string[] args)
        {
 
 
            DateTimeFormatInfo dtfi = System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat;
 
            string orginalFormatStr = dtfi.ShortDatePattern.ToString();
            Console.WriteLine("Show default: " + dtfi.ShortDatePattern);
 
            SetTimeFormat("yyyy/MMM/dd");
            SendMessage(HWND_BROADCAST, WM_SETTINGCHANGE, 0, 0); 
 
            dtfi = System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat;
            Console.WriteLine("Show change: " + dtfi.ShortDatePattern);
 
            SetTimeFormat(orginalFormatStr);
            dtfi = System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat;
            Console.WriteLine("Show recovery: " + dtfi.ShortDatePattern);
            Console.ReadLine();
        }
 
 
 
        public static void SetTimeFormat(string dateFormat)
        {
            try
            {
                int x = GetSystemDefaultLCID();
                SetLocaleInfo(x, LOCALE_SSHORTDATE, dateFormat);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
 
 
    }
}

你可能感兴趣的:(local)