C# 爬取 在线时间 设置 Windows系统时间

效果图:
在这里插入图片描述

请添加图片描述


最近发现自己的小主机每次关机后,时间都不准时,这个问题一般都是主板的电池没电导致的,某宝买一个即可,但毕竟是写程序的,为什么不能写一个程序校准呢,每次开机运行一下

请添加图片描述

时间来源:
北京时间官网
时间源是爬取北京时间的官网然后在进行字符串的分割得到需要的部分
请添加图片描述

C# 网络爬虫 抓取“北京标准时间“ 网页请求
这篇文章有详细介绍

在请求网页时,如果网络不通畅,导致网页加载比较慢,这时就会导致窗体的假死,所以需要在按钮里定义线程,让线程去执行这个方法

线程命名空间:

using System.Threading;

private void button1_Click(object sender, EventArgs e)
{
    
    
 Thread th = new Thread(Settime);//定义线程
th.IsBackground = true;//设置为后台线程
 th.Start();    //开始线程
}
//Settime方法
 SystemTime time = new SystemTime();//实例化结构
 
 string url = "http://time.tianqi.com/";//请求的网站
 HttpWebRequest a = (HttpWebRequest)WebRequest.Create(url);
 a.Timeout = 8000;//设置请求时间 1000=1秒
  HttpWebResponse b = (HttpWebResponse)a.GetResponse();
 using (Stream s = b.GetResponseStream())
 {
    
    
 using (StreamReader r = new StreamReader(s, Encoding.UTF8))
  {
    
    
  string str = r.ReadToEnd();
   int n = str.IndexOf(':');
 str = str.Substring(n + 1);
  n = str.IndexOf('。');
   str = str.Substring(0, n);
   
  //str得到时间=2021-10-31 00:41:39

经过字符串的分割 得到时间

2021-10-31 00:41:39

扫描二维码关注公众号,回复: 13741128 查看本文章

得到时间后因为C#不能直接的修改系统时间,但是可以调用系统的API函数来修改

命名空间:

using System.Runtime.InteropServices;

导入库:

 [DllImport("Kernel32.dll")]
public static extern bool SetLocalTime(ref SystemTime sysTime);

使用他参数必须是结构体,成员变量类型必须是ushort,成员变量不能改变顺序

定义结构:

public struct SystemTime
  {
    
    
 public ushort Year;//年
 public ushort Month;//月
 public ushort DayOfWeek;//星期 不需要理他(系统会自己算)
 public ushort Day;//日
 public ushort Hour;//小时
 public ushort Minute;//分钟
public ushort Second;//秒
 public ushort Miliseconds;//不需要理他
  }

结构是ushort类型的,这里就需要二次分割在进行转换成ushort类型在赋值给结构体

结构赋值:

int yearmath = str.IndexOf('-');
 time.Year = Convert.ToUInt16(str.Substring(0, yearmath));
 //年     

 time.Month = Convert.ToUInt16(str.Substring(yearmath + 1, 2));
//月

time.Day = Convert.ToUInt16(str.Substring(8, 3));
//日

 time.Hour = Convert.ToUInt16(str.Substring(10, 3));
 //小时
 
 time.Minute = Convert.ToUInt16(str.Substring(14, 2));
 //分钟
 
 time.Second = Convert.ToUInt16(str.Substring(17, 2));
//秒

给结构赋值后就可以直接调用API修改系统时间了

调用API:

 SetLocalTime(ref time);//记得先在方法实例化

这时系统时间已修改成功
请添加图片描述

设置开机执行:
请添加图片描述

怎么认开机的时候执行一次然后自己关闭程序呢?
可以把程序写入注册表,实现开机自启

命名空间:

using Microsoft.Win32;

设置注册表需要把程序的目录添加进去所以需要先获得自己的运行目录

获取自己根目录:

 public string str = Application.ExecutablePath+@"\\me";
 //序列化目录
 
 public  string path = System.Windows.Forms.Application.ExecutablePath;
 //程序详细目录
     

因为序列和反序列都需要使用到 必须是公共的
请添加图片描述
获取了自己的根目录后就可以写进注册表了,写进注册表后,虽然重新开机时会自动打开,但是并不会执行,这里使用"序列化"和"反序列号"存储选择信息

类存储信息:

[Serializable]
//表示这个类可以序列化
 public class FileMessage
 
 {
    
    
 private string _message; 
 //字段

 public string Message
{
    
    
get {
    
     return _message; }
set{
    
     _message = value;}      
//通过属性给他赋值
}
}

存储的写好后需要在 “选中” 时写入配置文本
这里需要使用到文件的写入

命名空间:

using System.IO;

序列化(写入):

 //序列化

FileStream file = new FileStream(@str, FileMode.Create);
 FileMessage me = new FileMessage();
 {
    
    
 me.Message = "开机启动";
 checkBox1.Checked = true;
}
 BinaryFormatter c = new BinaryFormatter(); //二进制格式化器
 c.Serialize(file, me);
 file.Close();
file.Dispose();

反序列化(读取):
窗口载入时

str = Environment.CurrentDirectory + "hzzk.jx";
FileStream fs = new FileStream(@str, FileMode.Open);
  BinaryFormatter c = new BinaryFormatter();
 FileMessage ob = (FileMessage)c.Deserialize(fs);
  fs.Close();
 fs.Dispose();
 this.label1.Text = ob.Message;

写入注册表(开机启动):

 RegistryKey RKey = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
RKey.SetValue("xiaoma", @str);

删除注册表(删除开机启动):

 RegistryKey RKey = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
 RKey.DeleteValue("xiaoma");

选择框完整代码:

 private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
    
     
 try
  {
    
    
 if (checkBox1.Checked)
 {
    
    
 //如果被选中
RegistryKey RKey = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
RKey.SetValue("xiaoma", @path);

 //序列化
FileStream file = new FileStream(@str, FileMode.Create);
FileMessage me = new FileMessage();
    {
    
    
me.Message = "开机启动";
checkBox1.Checked = true;
   }
BinaryFormatter c = new BinaryFormatter(); //二进制格式化器
  c.Serialize(file, me);
 file.Close();
file.Dispose();

}
 else
{
    
    
 if (File.Exists(str))
{
    
    
 File.Delete(str);
 }
 checkBox1.Text = "开机自动校对";
checkBox1.Checked = false;
 RegistryKey RKey = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
 RKey.DeleteValue("xiaoma");
                   
   }

 }
            catch 
 {
    
                
 }
}

如果 "选择框"的值是开机启动那么就开启线程执行方法
执行完成后倒计时五秒自动退出软件

添加一个计时器

自动退出程序:
开机5秒后自动关闭程序

int n=5;
 private void timer1_Tick(object sender, EventArgs e)
 {
    
    
 if (n == 0)
 {
    
    
 Process.GetCurrentProcess().Kill();//杀死进程
}
 n--;        
 }

窗口载入完整代码:

 private void Form1_Load(object sender, EventArgs e)
        {
    
    

            str = Environment.CurrentDirectory + "hzzk.jx";
            FileStream fs = new FileStream(@str, FileMode.Open);
            BinaryFormatter c = new BinaryFormatter();
            FileMessage ob = (FileMessage)c.Deserialize(fs);
            fs.Close();
            fs.Dispose();
             this.checkBox1.Text = ob.Message;


            if (checkBox1.Text=="开机启动")
            {
    
    
                Thread th = new Thread(Settime);
                th.IsBackground = true;
                th.Start();
                  timer1.Enabled = true;
            }

        }

全部代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.Win32;
using System.Runtime.Serialization.Formatters.Binary;
using System.Diagnostics;

namespace ServeTimeAdjust
{
    
    
    public partial class Form1 : Form
    {
    
    
        public Form1()
        {
    
    
            InitializeComponent();
        }



        public struct SystemTime
        {
    
    
            public ushort Year;
            public ushort Month;
            public ushort DayOfWeek;
            public ushort Day;
            public ushort Hour;
            public ushort Minute;
            public ushort Second;
            public ushort Miliseconds;
        }


        [DllImport("Kernel32.dll")]
        public static extern bool SetLocalTime(ref SystemTime sysTime);


        private void button1_Click(object sender, EventArgs e)
        {
    
    
            Thread th = new Thread(Settime);
            th.IsBackground = true;
            th.Start();
            
        }

        void Settime()
        {
    
    
            try {
    
    

                SystemTime time = new SystemTime();
                string url = "http://time.tianqi.com/";
                HttpWebRequest a = (HttpWebRequest)WebRequest.Create(url);
                a.Timeout = 8000;
                HttpWebResponse b = (HttpWebResponse)a.GetResponse();
                using (Stream s = b.GetResponseStream())
                {
    
    
                    using (StreamReader r = new StreamReader(s, Encoding.UTF8))
                    {
    
    
                        string str = r.ReadToEnd();
                        int n = str.IndexOf(':');
                        str = str.Substring(n + 1);
                        n = str.IndexOf('。');
                        str = str.Substring(0, n);
                        //str得到时间 2021-10-31 00:41:39


                        int yearmath = str.IndexOf('-');
                        time.Year = Convert.ToUInt16(str.Substring(0, yearmath));
                        //年     


                        time.Month = Convert.ToUInt16(str.Substring(yearmath + 1, 2));
                        //月


                        time.Day = Convert.ToUInt16(str.Substring(8, 3));
                        //日


                        time.Hour = Convert.ToUInt16(str.Substring(10, 3));
                        //小时


                        time.Minute = Convert.ToUInt16(str.Substring(14, 2));
                        //分钟



                        time.Second = Convert.ToUInt16(str.Substring(17, 2));
                        //秒

                        SetLocalTime(ref time);
                    }



                }

                }
            catch {
    
    
                MessageBox.Show("校对失败,请经常网络连接");
            
            
            }


            }

        private void Form1_Load(object sender, EventArgs e)
        {
    
    
            try
            {
    
    
                str = Environment.CurrentDirectory + "\\me";
                FileStream fs = new FileStream(@str, FileMode.Open);
                BinaryFormatter c = new BinaryFormatter();
                FileMessage ob = (FileMessage)c.Deserialize(fs);
                fs.Close();
                fs.Dispose();
                this.checkBox1.Text = ob.Message;


                if (checkBox1.Text == "开机启动")
                {
    
    
                    checkBox1.Checked = true;
                    Thread th = new Thread(Settime);
                    th.IsBackground = true;
                    th.Start();
                    timer1.Enabled = true;
                }
            }
            catch 
            {
    
     
            
            }
        }

        public string str = Application.ExecutablePath+@"\\me";
        public  string path = System.Windows.Forms.Application.ExecutablePath;
     
        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
    
    

        

            try
            {
    
    
                if (checkBox1.Checked)
                {
    
    
                    //如果被选中

                    RegistryKey RKey = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
                    RKey.SetValue("xiaoma", @path);


                    //序列化
                    FileStream file = new FileStream(@str, FileMode.Create);
                    FileMessage me = new FileMessage();
                    {
    
    
                        me.Message = "开机启动";
                        checkBox1.Checked = true;
                    }
                    BinaryFor


matter c = new BinaryFormatter(); //二进制格式化器
                    c.Serialize(file, me);
                    file.Close();
                    file.Dispose();




                }
                else
                {
    
    
                    if (File.Exists(str))
                    {
    
    
                        File.Delete(str);
                    }

                    checkBox1.Text = "开机自动校对";
                    checkBox1.Checked = false;
                    RegistryKey RKey = Registry.CurrentUser.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
                    RKey.DeleteValue("xiaoma");
                   
                }

            }
            catch 
            {
    
     
            
            }



        }
        int n = 5;
        private void timer1_Tick(object sender, EventArgs e)
        {
    
    
            if (n == 0)
            {
    
    
                Process.GetCurrentProcess().Kill();//杀死进程
            }
            n--;        
        }
    }

      
    }
            
   

纯手打,点个赞呗~

猜你喜欢

转载自blog.csdn.net/dpc5201314/article/details/121059168