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);
            }
        }
相关推荐
忧郁的蛋~1 小时前
.NET实现多任务异步与并行处理的详细步骤
后端·c#·asp.net·.net·.netcore
阿登林1 小时前
C# iText7与iTextSharp导出PDF对比
开发语言·pdf·c#
虚行3 小时前
WPF入门
开发语言·c#·wpf
djk88884 小时前
一个完整的 TCP 服务器监听示例(C#)
服务器·tcp/ip·c#
虚行6 小时前
C#技术栈
开发语言·c#
唐青枫7 小时前
C#.NET SqlKata 使用详解:优雅构建动态 SQL 查询
c#·.net
虚行15 小时前
C#上位机工程师技能清单文档
开发语言·c#
小白杨树树18 小时前
【C++】力扣hot100错误总结
c++·leetcode·c#
Tiger_shl18 小时前
三大并发集合ConcurrentDictionary、ConcurrentBag、ConcurrentQueue
开发语言·c#
时光追逐者20 小时前
一个使用 WPF 开发的 Diagram 画板工具(包含流程图FlowChart,思维导图MindEditor)
c#·.net·wpf·流程图