| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 |
- using Microsoft.Win32;
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace CCDCount.DLL.Tools
- {
- public class AutoStartHelper
- {
- // 注册表路径
- 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);
- }
- }
- }
- }
- }
|