C# winform程序实现开机自启动并且识别是开机启动还是双击启动

2020-01-05 09:53:06王旭
C#,winform,程序,开机,启动

核心代码:


using System;
using Microsoft.Win32;
namespace AutoStartRun
{
  public sealed class SystemHelper
  {
    private SystemHelper() { }
    /// <summary>
    /// 设置程序开机启动
    /// </summary>
    /// <param name="strAppPath">应用程序exe所在文件夹</param>
    /// <param name="strAppName">应用程序exe名称</param>
    /// <param name="bIsAutoRun">自动运行状态</param>
    public static void SetAutoRun(string strAppPath, string strAppName, bool bIsAutoRun)
    {
      try
      {
        if (string.IsNullOrWhiteSpace(strAppPath)
          || string.IsNullOrWhiteSpace(strAppName))
        {
          throw new Exception("应用程序路径或名称为空!");
        }
        RegistryKey reg = Registry.LocalMachine;
        RegistryKey run = reg.CreateSubKey(@"SOFTWAREMicrosoftWindowsCurrentVersionRun");
        if (bIsAutoRun)
        {
          run.SetValue(strAppName, strAppPath);
        }
        else
        {
          if (null != run.GetValue(strAppName))
          {
            run.DeleteValue(strAppName);
          }
        }
        run.Close();
        reg.Close();
      }
      catch (Exception ex)
      {
        throw new Exception(ex.Message, ex);
      }
    }
    /// <summary>
    /// 判断是否开机启动
    /// </summary>
    /// <param name="strAppPath">应用程序路径</param>
    /// <param name="strAppName">应用程序名称</param>
    /// <returns></returns>
    public static bool IsAutoRun(string strAppPath, string strAppName)
    {
      try
      {
        RegistryKey reg = Registry.LocalMachine;
        RegistryKey software = reg.OpenSubKey(@"SOFTWARE");
        RegistryKey run = reg.OpenSubKey(@"SOFTWAREMicrosoftWindowsCurrentVersionRun");
        object key = run.GetValue(strAppName);
        software.Close();
        run.Close();
        if (null == key || !strAppPath.Equals(key.ToString()))
        {
          return false;
        }
        return true;
      }
      catch (Exception ex)
      {
        throw new Exception(ex.Message, ex);
      }
    }
  }
}

 调用方法:


 /// <summary>
    /// 设置程序开机自启动
    /// </summary>
    private void SetAutoRun()
    {
      string strFilePath = Application.ExecutablePath;
      string strFileName = System.IO.Path.GetFileName(strFilePath);
      try
      {
        SystemHelper.SetAutoRun(strFilePath + " -autostart", strFileName, !menuAutoRun.Checked);
        menuAutoRun.Checked = !menuAutoRun.Checked;
      }
      catch (Exception ex)
      {
        MessageBox.Show(this, ex.Message, "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
      }
    }