主要功能
一行代码
private void checkBoxAutoRun_CheckedChanged(object sender, EventArgs e)
{
this.ExRunOnSystemStart(checkBoxAutoRun.Checked);
}
代码封装
/// <summary>
/// 设置是否开机启动
/// </summary>
/// <param name="theForm"></param>
/// <param name="isRunOnStart">是否开机启动</param>
public static void ExRunOnSystemStart(this Form theForm, bool isRunOnStart)
{
//HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
const string item = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Run";
string exeName = Path.GetFileNameWithoutExtension(Application.ExecutablePath);
string exePath = "\"" + Application.ExecutablePath + "\"";
try
{
if (Registry.LocalMachine.OpenSubKey(item) == null) Registry.LocalMachine.CreateSubKey(item);
using (RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(item, true))
{
if (isRunOnStart)
registryKey.SetValue(exeName, exePath);
else
registryKey.DeleteValue(exeName);
}
}
catch (Exception ex)
{
ProviderTrace.TraceError(ex);
}
}
/// <summary>
/// 切换开机启动
/// </summary>
/// <param name="theForm"></param>
/// <returns></returns>
public static bool ExSwitchRunOnSystemStart(this Form theForm)
{
bool isRunOnStart = !theForm.ExIsRunOnSystemStart();
theForm.ExRunOnSystemStart(isRunOnStart);
return isRunOnStart;
}
/// <summary>
/// 获取是否开机启动
/// </summary>
/// <param name="theForm"></param>
/// <returns></returns>
public static bool ExIsRunOnSystemStart(this Form theForm)
{
//HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
const string item = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Run";
string exeName = Path.GetFileNameWithoutExtension(Application.ExecutablePath);
string exePath = Application.ExecutablePath;
try
{
if (Registry.LocalMachine.OpenSubKey(item) == null) Registry.LocalMachine.CreateSubKey(item);
using (RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(item, true))
{
object value = registryKey.GetValue(exeName);
if (value == null) return false;
registryKey.SetValue(exeName, exePath);
return true;
}
}
catch (Exception ex)
{
ProviderTrace.TraceError(ex);
return false;
}
}
声明