using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MvvmScaffoldFrame48.DLL.SystemTools
{
public class AutoStartHelper
{
///
/// 若出现自启动时相对路径异常的情况可以在程序启动时引用如下代码
/// Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
///
// 注册表路径
private static readonly string RegistryPath = @"Software\Microsoft\Windows\CurrentVersion\Run";
// 应用名称,作为注册表键名
private static readonly string AppName = "CCDCount";
///
/// 获取当前可执行文件路径
///
public static string GetExecutablePath()
{
return Process.GetCurrentProcess().MainModule.FileName;
}
///
/// 检查是否已设置自启动
///
public static bool IsAutoStart()
{
using (var key = Registry.CurrentUser.OpenSubKey(RegistryPath, false))
{
if (key == null) return false;
var value = key.GetValue(AppName);
// 验证路径是否一致,防止exe移动后失效
return value != null && value.ToString() == GetExecutablePath();
}
}
///
/// 设置或取消自启动
///
/// true 为启用,false 为禁用
public static void SetAutoStart(bool isAutoStart)
{
using (var key = Registry.CurrentUser.OpenSubKey(RegistryPath, true))
{
if (key == null) return;
if (isAutoStart)
{
if (!IsAutoStart())
{
key.SetValue(AppName, GetExecutablePath());
}
}
else
{
// false 参数表示值不存在时不抛出异常
key.DeleteValue(AppName, false);
}
}
}
}
}