filesSync/StartupRegistration.cs
2026-12-06 15:47:51 +08:00

44 lines
1.4 KiB
C#

using System;
using System.IO;
using System.Windows.Forms;
using Microsoft.Win32;
internal static class StartupRegistration
{
public const string BackgroundArgument = "--background";
private const string RunKey = @"Software\Microsoft\Windows\CurrentVersion\Run";
private const string ValueName = "DailyFileSync";
private static string StartupCommand
{
get { return "\"" + Application.ExecutablePath + "\" " + BackgroundArgument; }
}
public static bool IsEnabled()
{
using (RegistryKey key = Registry.CurrentUser.OpenSubKey(RunKey))
{
string command = key == null ? null : key.GetValue(ValueName) as string;
return String.Equals(command, StartupCommand, StringComparison.OrdinalIgnoreCase);
}
}
public static void SetEnabled(bool enabled)
{
if (enabled)
{
string command = StartupCommand;
if (command.Length > 260)
throw new IOException("程序路径太长,无法设置开机自动启动。请将程序移到路径较短的目录后重试。");
using (RegistryKey key = Registry.CurrentUser.CreateSubKey(RunKey))
key.SetValue(ValueName, command, RegistryValueKind.String);
}
else
{
using (RegistryKey key = Registry.CurrentUser.OpenSubKey(RunKey, true))
if (key != null) key.DeleteValue(ValueName, false);
}
}
}