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 小时前
c#:TCP服务端管理类
java·tcp/ip·c#
SchuylerEX3 小时前
第六章 JavaScript 互操(2).NET调用JS
前端·c#·.net·blazor·ui框架
★YUI★3 小时前
学习游戏制作记录(制作系统与物品掉落系统)8.16
学习·游戏·ui·unity·c#
mit6.82412 小时前
Linux下C#项目构建
开发语言·c#
Nita.13 小时前
.NET 中的延迟初始化:Lazy<T> 与LazyInitializer
c#·.net
好望角雾眠1 天前
第一阶段C#基础-10:集合(Arraylist,list,Dictionary等)
笔记·学习·c#
忒可君1 天前
C# winform FTP功能
开发语言·windows·c#
时光追逐者1 天前
C#/.NET/.NET Core技术前沿周刊 | 第 50 期(2025年8.11-8.17)
c#·.net·.netcore·.net core
一个会的不多的人1 天前
C# NX二次开发:操作按钮控件Button和标签控件Label详解
开发语言·c#
咕白m6251 天前
C# 实现 PDF 转图片 - 分辨率设置、图片格式选择
后端·c#