先上核心代码
public class AutoStartUPHelper
{
/// <summary>
/// 开机自启动
/// </summary>
/// <param name="ButtinPath">执行文件路径</param>
public void RegisterAutoStartUP(string KeyName,string ButtinPath)//"FacePC客户端"
{
using (RegistryKey rk = Registry.LocalMachine)
{
RegistryKey runKey = rk.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
if (runKey == null)
{
runKey = Registry.LocalMachine.CreateSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run");
}
try
{
runKey.SetValue(KeyName, ButtinPath);
runKey.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
runKey.Close();
}
}
}
/// <summary>
/// 删除开机自启动
/// </summary>
/// <param name="ButtinPath">执行文件路径</param>
public void CancelAutoStartUP(string KeyName)//
{
using (RegistryKey reg = Registry.LocalMachine)
{
RegistryKey runKey = reg.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
if (runKey == null)
{
runKey = Registry.LocalMachine.CreateSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run");
}
try
{
//string keyValue = destPath + exeName;
runKey.DeleteValue(KeyName, true);
runKey.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
runKey.Close();
}
}
}
}
代码很简单 但是我测试的时候老是注册失败 后来发现一个奇葩的问题:我测试时候使用的路径路径分隔符为“/” 这样注册出来虽然程序出现在了启动项 但是点击打开服务所在文件路径会没反应 ,尝试多次后改路径间隔符为“\” .然后终于成功了 mmp 看来操作注册表路径间隔符必须为“\”