public static class AutoStartManager{
private const string RunRegistryKey = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run";
public static bool IsAutoStartEnabled()
{
using (RegistryKey key = Registry.CurrentUser.OpenSubKey(RunRegistryKey, false))
{
return key.GetValue(System.Diagnostics.Process.GetCurrentProcess().ProcessName) != null;
}
}
public static void EnableAutoStart()
{
using (RegistryKey key = Registry.CurrentUser.OpenSubKey(RunRegistryKey, true))
{
key.SetValue(System.Diagnostics.Process.GetCurrentProcess().ProcessName, System.Reflection.Assembly.GetEntryAssembly().Location);
}
}
public static void DisableAutoStart()
{
using (RegistryKey key = Registry.CurrentUser.OpenSubKey(RunRegistryKey, true))
{
key.DeleteValue(System.Diagnostics.Process.GetCurrentProcess().ProcessName, false);
}
}
}
//接下来,在您的WPF应用程序中,在需要设置开机自启动的地方调用 EnableAutoStart() 方法即可将应用程序添加到开机自启动项。例如,您可以在应用程序的设置页面或者启动窗口中提供一个复选框,允许用户选择是否开启开机自启动功能。
{
AutoStartManager.EnableAutoStart();
}
else{
AutoStartManager.DisableAutoStart();
}
//请注意,修改注册表需要管理员权限,因此在运行代码时,确保您的应用程序以管理员身份运行。此外,开机自启动功能通常在用户登录时启动,而不是在计算机启动时立即启动。