C# 通过代码开启自动设置时间和自动设置时区选项

自动设置时间,需要看两个值,一个是W32Time下的Parameters里的Type值还有一个是W32Time本身下面的一个Start的值,这两个值设置自动就可以了,单独设置其中一个是不行的必须同时设置。

cs 复制代码
 private void isAutoTimeSetting()
        {
            bool isParametersAuto = false;
            string keyName = @"SYSTEM\CurrentControlSet\Services\W32Time\Parameters";
            using (RegistryKey rKey = Registry.LocalMachine.OpenSubKey(keyName))
            {
                if (rKey != null && rKey.GetValue("Type") != null)
                {
                    string value = rKey.GetValue("Type").ToString();
                    if (value == "NTP")
                    {
                        isParametersAuto = true;
                    }
                    else if (value == "NoSync")
                    {
                        isParametersAuto = false;
                    }
                }
                rKey.Close();
            }

            bool isStartAuto = false;
            string keyName1 = @"SYSTEM\CurrentControlSet\Services\W32Time";
            using (RegistryKey rKey = Registry.LocalMachine.OpenSubKey(keyName1))
            {
                if (rKey != null && rKey.GetValue("Start") != null)
                {
                    string value = rKey.GetValue("Start").ToString();
                    if (value == "3")
                    {
                        isStartAuto = true;
                    }
                    else if (value == "4")
                    {
                        isStartAuto = false;
                    }
                }
                rKey.Close();
            }
            if (isStartAuto && isParametersAuto)
            {
                AppendText(1, $"<Color>已经勾选为自动设置时间</Color>\n", Color.Green);
            }
            else
            {
                string tip = "未勾选为自动设置时间";
                AppendText(1, $"<Color>{tip}</Color>,请检查!\n", Color.Red);
                ErrorAdd(ErrorCode.systemTimeAutoSetting, tip);
            }
        }
相关推荐
yue0086 小时前
C# 更改窗体样式
开发语言·c#
Charles_go7 小时前
C#中级1、元祖和值元组有什么区别
c#
C#程序员一枚10 小时前
导出百万量数据到Excel表
c#·excel
攻城狮CSU12 小时前
C# 异步方法
开发语言·前端·c#
ekkcole12 小时前
java word转pdf工具类,兼容linux和windows服务器
开发语言·pdf·c#
yangshuquan13 小时前
C# 委托和事件的3点区别,你知道几个?
c#·委托·事件·编程技巧
她说彩礼65万18 小时前
C# Lambda 表达式
开发语言·c#
烛阴19 小时前
C#常量(const)与枚举(enum)使用指南
前端·c#
阿Y加油吧20 小时前
java并发编程面试题精讲——day02
java·面试·c#
唐青枫21 小时前
C#.NET DateTime 最强入门到进阶:格式化、转换、UTC、时区全覆盖
c#·.net