AuToManager.cs 3.0 KB
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AuToRunManager
{
    class AuToManager
    {

        public static void AutoRun(string filePath,bool isAuto)
        {             
            string strnewName = filePath.Substring(filePath.LastIndexOf("\\") + 1);
            if (isAuto)
            { 
                RegistryKey Local = Registry.LocalMachine;
                RegistryKey runKey = Local.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run\");
                runKey.SetValue(strnewName, filePath);
                Local.Close();
                MessageBox.Show("程序"+strnewName+"开机启动设置完成,重新启动计算机后即可生效!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                //修改注册表,使程序开机时不自动执行。             
                Microsoft.Win32.RegistryKey Rkey = Microsoft.Win32.Registry.LocalMachine.CreateSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run");
                Rkey.DeleteValue(strnewName, false);
                Rkey.Close();
                MessageBox.Show("程序" + strnewName + "开机启动已取消!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        public static void AutoRun(object[] args)
        {
            if (args.Length > 2)
            {
                try
                {
                    RegistryKey Local = Registry.LocalMachine;
                    RegistryKey runKey = Local.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run\");
                    Microsoft.Win32.RegistryKey Rkey = Microsoft.Win32.Registry.LocalMachine.CreateSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run");

                    for (int i = 0; i < args.Length; i = i + 2)
                    {
                        string filePath = args[i].ToString();
                        bool isAuto = Boolean.Parse(args[i + 1].ToString());
                        string strnewName = filePath.Substring(filePath.LastIndexOf("\\") + 1);
                        if (isAuto)
                        {

                            runKey.SetValue(strnewName, filePath);
                        }
                        else
                        {
                            //修改注册表,使程序开机时不自动执行。             
                            Rkey.DeleteValue(strnewName, false);

                        }
                    }
                    Local.Close();
                    Rkey.Close();
                    MessageBox.Show("程序设置完成,重新启动计算机后即可生效!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString(), "错误");
                }
            }
        }
    }
}