| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869 |
- 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
- {
- /// <summary>
- /// 若出现自启动时相对路径异常的情况可以在程序启动时引用如下代码
- /// Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
- /// </summary>
- // 注册表路径
- private static readonly string RegistryPath = @"Software\Microsoft\Windows\CurrentVersion\Run";
- // 应用名称,作为注册表键名
- private static readonly string AppName = "CCDCount";
- /// <summary>
- /// 获取当前可执行文件路径
- /// </summary>
- public static string GetExecutablePath()
- {
- return Process.GetCurrentProcess().MainModule.FileName;
- }
- /// <summary>
- /// 检查是否已设置自启动
- /// </summary>
- 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();
- }
- }
- /// <summary>
- /// 设置或取消自启动
- /// </summary>
- /// <param name="isAutoStart">true 为启用,false 为禁用</param>
- 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);
- }
- }
- }
- }
- }
|