C# 爬取 在线时间 设置 Windows系统时间
效果图:
最近发现自己的小主机每次关机后,时间都不准时,这个问题一般都是主板的电池没电导致的,某宝买一个即可,但毕竟是写程序的,为什么不能写一个程序校准呢,每次开机运行一下即可,
玩玩就即可还是要去换一个电池的…
时间来源:
北京时间官网
时间源是爬取北京时间的官网然后在进行字符串的分割得到需要的部分
C# 网络爬虫 抓取“北京标准时间“ 网页请求
这篇文章有详细介绍
在请求网页时,如果网络不通畅,导致网页加载比较慢,这时就会导致窗体的假死,所以需要在按钮里定义线程,让线程去执行这个方法
线程命名空间:
using System.Threading;
private void button1_Click(object sender, EventArgs e)
{
Thread th = new Thread(Settime);//定义线程
th.IsBackground = true;//设置为后台线程
th.Start(); //开始线程
}
- 1
- 2
- 3
- 4
- 5
- 6
//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
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
经过字符串的分割 得到时间
2021-10-31 00:41:39
得到时间后因为C#不能直接的修改系统时间,但是可以调用系统的API函数来修改
命名空间:
using System.Runtime.InteropServices;
导入库:
[DllImport("Kernel32.dll")]
public static extern bool SetLocalTime(ref SystemTime sysTime);
- 1
- 2
使用他参数必须是结构体,成员变量类型必须是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;//不需要理他
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
结构是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));
//秒
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
给结构赋值后就可以直接调用API修改系统时间了
调用API:
SetLocalTime(ref time);//记得先在方法实例化
- 1
这时系统时间已修改成功
设置开机执行:
怎么认开机的时候执行一次然后自己关闭程序呢?
可以把程序写入注册表,实现开机自启
命名空间:
using Microsoft.Win32;
设置注册表需要把程序的目录添加进去所以需要先获得自己的运行目录
获取自己根目录:
public string str = Application.ExecutablePath+@"\me";
//序列化目录
public string path = System.Windows.Forms.Application.ExecutablePath;
//程序详细目录
- 1
- 2
- 3
- 4
- 5
- 6
因为序列和反序列都需要使用到 必须是公共的
获取了自己的根目录后就可以写进注册表了,写进注册表后,虽然重新开机时会自动打开,但是并不会执行,这里使用"序列化"和"反序列号"存储选择信息
类存储信息:
[Serializable]
//表示这个类可以序列化
public class FileMessage
{
private string _message;
//字段
public string Message
{
get { return _message; }
set{ _message = value;}
//通过属性给他赋值
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
存储的写好后需要在 “选中” 时写入配置文本
这里需要使用到文件的写入
命名空间:
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();
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
反序列化(读取):
窗口载入时
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;
- 1
- 2
- 3
- 4
- 5
- 6
- 7
写入注册表(开机启动):
RegistryKey RKey = Registry.CurrentUser.CreateSubKey(@"SOFTWAREMicrosoftWindowsCurrentVersionRun");
RKey.SetValue("xiaoma", @str);
- 1
- 2
删除注册表(删除开机启动):
RegistryKey RKey = Registry.CurrentUser.CreateSubKey(@"SOFTWAREMicrosoftWindowsCurrentVersionRun");
RKey.DeleteValue("xiaoma");
- 1
- 2
选择框完整代码:
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
try
{
if (checkBox1.Checked)
{
//如果被选中
RegistryKey RKey = Registry.CurrentUser.CreateSubKey(@"SOFTWAREMicrosoftWindowsCurrentVersionRun");
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(@"SOFTWAREMicrosoftWindowsCurrentVersionRun");
RKey.DeleteValue("xiaoma");
}
}
catch
{
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
如果 "选择框"的值是开机启动那么就开启线程执行方法
执行完成后倒计时五秒自动退出软件
添加一个计时器
自动退出程序:
开机5秒后自动关闭程序
int n=5;
private void timer1_Tick(object sender, EventArgs e)
{
if (n == 0)
{
Process.GetCurrentProcess().Kill();//杀死进程
}
n--;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
窗口载入完整代码:
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;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
全部代码:
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(@"SOFTWAREMicrosoftWindowsCurrentVersionRun");
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(@"SOFTWAREMicrosoftWindowsCurrentVersionRun");
RKey.DeleteValue("xiaoma");
}
}
catch
{
}
}
int n = 5;
private void timer1_Tick(object sender, EventArgs e)
{
if (n == 0)
{
Process.GetCurrentProcess().Kill();//杀死进程
}
n--;
}
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109
- 110
- 111
- 112
- 113
- 114
- 115
- 116
- 117
- 118
- 119
- 120
- 121
- 122
- 123
- 124
- 125
- 126
- 127
- 128
- 129
- 130
- 131
- 132
- 133
- 134
- 135
- 136
- 137
- 138
- 139
- 140
- 141
- 142
- 143
- 144
- 145
- 146
- 147
- 148
- 149
- 150
- 151
- 152
- 153
- 154
- 155
- 156
- 157
- 158
- 159
- 160
- 161
- 162
- 163
- 164
- 165
- 166
- 167
- 168
- 169
- 170
- 171
- 172
- 173
- 174
- 175
- 176
- 177
- 178
- 179
- 180
- 181
- 182
- 183
- 184
- 185
- 186
- 187
- 188
- 189
- 190
- 191
- 192
- 193
- 194
- 195
- 196
- 197
- 198
- 199
- 200
- 201
- 202
- 203
- 204
- 205
- 206
- 207
- 208
- 209
- 210
- 211
- 212
- 213
- 214
- 215
- 216
- 217
- 218
- 219
纯手打,点个赞呗~