C#一行代码实现之设置开机启动

代码应用

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;
    }
}

 

posted @ 2023-05-06 17:21  懒树懒  阅读(147)  评论(0)    收藏  举报