前言
在工业领域,部分项目要求开发者增加软件开机自启动功能。
这里大概有两种方法来实现这一功能,这里我们以winform桌面应用程序为例,采用第一种方法:修改注册表的形式来实现这一功能
1.修改计算机注册表的方式
2.将软件的快捷方式创建到计算机的自动启动目录下
提示:以下是本篇文章正文内容,下面案例可供参考
一、配置文件
在应用程序的开发中,用于持久化配置的配置文件有json、xml、ini、properties等文件形式,我们先以json为例
二、使用步骤
1.引入库
我们需要对json文件进行序列化和反序列化,这里我们可以使用第三方库来简化我们的开发,这里我们以比较出名的Newtonsoft.Json.dll这个第三方库为例
没有网络:引用->添加引用->浏览->浏览->选择本地的dll文件->引用命名空间
有网络:引用->管理Nuget程序包->浏览->搜索json->安装->引用命名空间
2.功能逻辑
1.在form中仅添加一个checkbox控件(示例):并命名为:ckbAutoLaunch
2.在根目录下添加一个json文件,名字随意啦,我这里命名为appSettings.json
{
"IsAutoLaunch": false,
"IsTop": true
}
2.在程序/窗体加载的过程中,我们需要从配置文件中拿到是否为自启动,并给ckbAutoLaunch控件的checked属性赋值
private void Form1_Load(object sender, EventArgs e)
{
ckbAutoLaunch.Checked = ReadJson("IsAutoLaunch");
}
3.编写ReadJson(string key)方法
/// <summary>
/// 读取json配置文件,在窗体load事件中给checkbox 的checked属性赋值
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
private bool ReadJson(string key)
{
// 可以把下面的代码放在try catch 中,并结合日志文件打印输出
string path = Application.StartupPath + @"\Properties\appSettings.json";
//StreamRead 和 StreamWriter 只能读写文本文件,比如txt,log,json... 读取写入非文本文件,比如多媒体文件可以考虑使用FileStream类
using(StreamReader sr = new StreamReader(path))
{
string jsonStr = sr.ReadToEnd();
// 对读到的json字符串进行反序列化
Dictionary<string,object> jsonObj = JsonConvert.DeserializeObject<Dictionary<string,object>>(jsonStr);
//dynamic jsonObj = JsonConvert.DeserializeObject<dynamic>(jsonStr); // 用dynamic作为泛型类或许更好
return (bool)jsonObj[key];
}
}
4.注册checkbox 的 CheckedChanged 事件,并根据checked属性在系统注册表中添加不同的键值对,最后持久化到json文件中
private void ckbAutoLaunch_CheckedChanged(object sender, EventArgs e)
{
// 获取带有可执行文件名字的的路径
string execPath = Application.ExecutablePath;
string regPath = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run";
string execFileName = Path.GetFileName(execPath);
RegistryKey rk = Registry.LocalMachine.OpenSubKey(regPath,true);
if(rk == null)
{
rk = Registry.LocalMachine.CreateSubKey(regPath);
}
if(ckbAutoLaunch.Checked)
{
rk.SetValue(execFileName, execPath);
}
else
{
rk.DeleteValue(execFileName,false);
}
rk.Close();
// 将checkbox的勾选结果持久化到json文件中
WriteJson("IsAutoLaunch", ckbAutoLaunch.Checked);
}
5.编写WriteJson(string key, bool flag)方法
/// <summary>
/// 写入json,修改后写入
/// </summary>
/// <param name="key"></param>
/// <param name="checked"></param>
private void WriteJson(string key, bool Ischecked)
{
string path = Application.StartupPath + @"\Properties\appSettings.json";
string newJsonStr = "";
using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
byte[] buffer = new byte[1024 * 1024 * 5];
int r = fs.Read(buffer, 0, buffer.Length);
string jsonStr = Encoding.Default.GetString(buffer, 0, r);
dynamic jsonObj = JsonConvert.DeserializeObject<dynamic>(jsonStr);
jsonObj[key] = Ischecked;
// 序列化Json对象
newJsonStr = JsonConvert.SerializeObject(jsonObj, Formatting.Indented);
/*byte[] newBuffer = Encoding.Default.GetBytes(newJsonStr);
File.Delete(path);
fs.Write(newBuffer, 0, newBuffer.Length);*/
}
File.WriteAllText(path, newJsonStr);
}
6完整代码:
using Microsoft.Win32;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AutoLaunch_Test
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
ckbAutoLaunch.Checked = ReadJson("IsAutoLaunch");
}
/// <summary>
/// 读取json配置文件,在窗体load事件中给checkbox 的checked属性赋值
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
private bool ReadJson(string key)
{
// 可以把下面的代码放在try catch 中,并结合日志文件打印输出
string path = Application.StartupPath + @"\Properties\appSettings.json";
//StreamRead 和 StreamWriter 只能读写文本文件,比如txt,log,json... 读取写入非文本文件,比如多媒体文件可以考虑使用FileStream类
using(StreamReader sr = new StreamReader(path))
{
string jsonStr = sr.ReadToEnd();
// 对读到的json字符串进行反序列化
Dictionary<string,object> jsonObj = JsonConvert.DeserializeObject<Dictionary<string,object>>(jsonStr);
//dynamic jsonObj = JsonConvert.DeserializeObject<dynamic>(jsonStr); // 用dynamic作为泛型类或许更好
return (bool)jsonObj[key];
}
}
/// <summary>
/// 写入json,修改后写入
/// </summary>
/// <param name="key"></param>
/// <param name="checked"></param>
private void WriteJson(string key, bool Ischecked)
{
string path = Application.StartupPath + @"\Properties\appSettings.json";
string newJsonStr = "";
using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
byte[] buffer = new byte[1024 * 1024 * 5];
int r = fs.Read(buffer, 0, buffer.Length);
string jsonStr = Encoding.Default.GetString(buffer, 0, r);
dynamic jsonObj = JsonConvert.DeserializeObject<dynamic>(jsonStr);
jsonObj[key] = Ischecked;
// 序列化Json对象
newJsonStr = JsonConvert.SerializeObject(jsonObj, Formatting.Indented);
/*byte[] newBuffer = Encoding.Default.GetBytes(newJsonStr);
File.Delete(path);
fs.Write(newBuffer, 0, newBuffer.Length);*/
}
File.WriteAllText(path, newJsonStr);
}
private void ckbAutoLaunch_CheckedChanged(object sender, EventArgs e)
{
// 获取带有可执行文件名字的的路径
string execPath = Application.ExecutablePath;
string regPath = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run";
string execFileName = Path.GetFileName(execPath);
RegistryKey rk = Registry.LocalMachine.OpenSubKey(regPath,true);
if(rk == null)
{
rk = Registry.LocalMachine.CreateSubKey(regPath);
}
if(ckbAutoLaunch.Checked)
{
rk.SetValue(execFileName, execPath);
}
else
{
rk.DeleteValue(execFileName,false);
}
rk.Close();
// 将checkbox的勾选结果持久化到json文件中
WriteJson("IsAutoLaunch", ckbAutoLaunch.Checked);
}
}
}
总结
经过楼主测试,上述代码已经在楼猪电脑上测试成功 ,o( ̄▽ ̄)ブ
by the way
一些靓仔可能会出现没有管理员权限而无法往注册表中写入或者修改数据而报错,这里楼主看了其他文章,把Registry.LocalMachine.OpenSubKey(regPath,true) 改成Registry.CurrentUser.OpenSubKey(regPath, true);
大多数情况下都能解决这个问题,祝大家工作顺利
//RegistryKey rk = Registry.LocalMachine.OpenSubKey(regPath,true);
RegistryKey rk = Registry.CurrentUser.OpenSubKey(regPath, true);
这里特别感谢
参考1:WinFrom应用程序开机自启动
参考2:WinForm设置电脑开机自动启动程序
参考3:C#程序实现软件开机自动启动的两种常用方法