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);
            }
        }
相关推荐
懒人咖7 小时前
缺料分析时携带用料清单的二开字段
c#·金蝶云星空
bugcome_com8 小时前
深入了解 C# 编程环境及其开发工具
c#
wfserial10 小时前
c#使用微软自带speech选择男声仍然是女声的一种原因
microsoft·c#·speech
阔皮大师11 小时前
INote轻量文本编辑器
java·javascript·python·c#
kylezhao201912 小时前
C# 中的 SOLID 五大设计原则
开发语言·c#
啦啦啦_999912 小时前
Redis-5-doFormatAsync()方法
数据库·redis·c#
Porco.w13 小时前
C#与三菱PLC FX5U通信
网络·c#
E_ICEBLUE15 小时前
PPT 批量转图片:在 Web 预览中实现翻页效果(C#/VB.NET)
c#·powerpoint·svg
JQLvopkk17 小时前
C# 轻量级工业温湿度监控系统(含数据库与源码)
开发语言·数据库·c#
wxin_VXbishe19 小时前
C#(asp.net)学员竞赛信息管理系统-计算机毕业设计源码28790
java·vue.js·spring boot·spring·django·c#·php